最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change background color of button using react - Stack Overflow

programmeradmin8浏览0评论

I am working on react using bootstrap, initially I am giving same colors to my buttons, now What I am trying to do is on click of button change that button's color and if I click on other button it change the color of that and the first one back to basic (default) color

I have done this using jquery earlier as passing onclick event and toggle the color but here I am new to react so don't know how to do that.

My code

code sandbox

What I am looking for is suppose I have 7 buttons and I click on first one then its color should change , then If I am clicking on next button then first should e to normal and the clicked (second) one should changed the color.

Important the first button should always be in active mode i.e it should have the active color then if next clicked that color changes to normal and the clicked one should take the color

import React from 'react'

function Stddata() {
    const button_Data = [
      {
        "name": "Name",
        "value": "name"
      },
      {
        "name": "Class",
        "value": "class"
      },
      {
        "name": "Age",
        "value": "age"
      },
      {
        "name": "Subjects",
        "value": "subjects"
      },
      {
        "name": "School",
        "value": "school"
      }
    ]
    return (
        <div>
            { button_Data.map(item => (
                <div key={item.value}>
            <button 
                className="btn btn-outline-secondary mb-1 form-control text-left"
                value={item.value}
                onClick={props.trigerOnClickEmpSideBtn}
            >{item.name}</button>
            </div>
            ))}   
        </div>
    )
}

export default Stddata

I am working on react using bootstrap, initially I am giving same colors to my buttons, now What I am trying to do is on click of button change that button's color and if I click on other button it change the color of that and the first one back to basic (default) color

I have done this using jquery earlier as passing onclick event and toggle the color but here I am new to react so don't know how to do that.

My code

code sandbox

What I am looking for is suppose I have 7 buttons and I click on first one then its color should change , then If I am clicking on next button then first should e to normal and the clicked (second) one should changed the color.

Important the first button should always be in active mode i.e it should have the active color then if next clicked that color changes to normal and the clicked one should take the color

import React from 'react'

function Stddata() {
    const button_Data = [
      {
        "name": "Name",
        "value": "name"
      },
      {
        "name": "Class",
        "value": "class"
      },
      {
        "name": "Age",
        "value": "age"
      },
      {
        "name": "Subjects",
        "value": "subjects"
      },
      {
        "name": "School",
        "value": "school"
      }
    ]
    return (
        <div>
            { button_Data.map(item => (
                <div key={item.value}>
            <button 
                className="btn btn-outline-secondary mb-1 form-control text-left"
                value={item.value}
                onClick={props.trigerOnClickEmpSideBtn}
            >{item.name}</button>
            </div>
            ))}   
        </div>
    )
}

export default Stddata
Share Improve this question edited Apr 24, 2020 at 5:52 Devang 4541 gold badge8 silver badges19 bronze badges asked Apr 21, 2020 at 16:21 manish thakurmanish thakur 82010 gold badges43 silver badges83 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 3

You'll need to use some state. In your ponent, let's define which button is currently active. We can use useState and set its starting value to 0, as you said you want to the first button to start out as active:

import React, { useState } from 'react'

// inside your ponent
  const [activeButton, setActiveButton] = useState(0)

And your button's onClick will reference the function to change the currently active button. Within the className, it will check if its own index is the same as the currently active button, and set the css class accordingly:

{button_Data.map((item, index) => (
  <button 
    className={`btn ${activeButton === index ? 'btn-success' : null}`}  
    value={item.value} 
    onClick={ () => {setActiveButton(index)} }
  >

    {item.name}

  </button>
))}

Edit: Adding Working Demo

I actually had to break off each button into its own ponent because each button now needs to manage its own state. The underlying principle is the same, but each button is now its own ponent with its own state.

Edit 2:

With the changes to the initial quesiton, I changed the answer. The codesandbox also reflects these changes. The codesandbox still uses a separate ponent for the button, though that's not really necessary based on the new question parameters - but the principle is the same.

What you need to do is to store an active state for the button, default the state to the name of the first button.

Once you do that you can set an active className for the button which is selected.

onClick event of the button update the activeButton state.

const button_Data = [
  {
    name: "Name",
    value: "name"
  },
  {
    name: "Class",
    value: "class"
  },
  {
    name: "Age",
    value: "age"
  },
  {
    name: "Subjects",
    value: "subjects"
  },
  {
    name: "School",
    value: "school"
  }
];
function Stddata(props) {
  const [activeButton, setActiveButton] = useState(button_Data[0].name);
  const handleClick = e => {
    const name = e.target.name;
    setActiveButton(name);
  };
  return (
    <div>
      {button_Data.map(item => {
        const className = activeButton === item.name ? "active" : "";
        return (
          <div key={item.value}>
            <button
              className={`btn btn-outline-secondary mb-1 form-control text-left ${className}`}
              name={item.name}
              value={item.value}
              onClick={handleClick}
            >
              {item.name}
            </button>
          </div>
        );
      })}
    </div>
  );
}

export default Stddata;

Working demo

use this ponent for buttons

    import React from 'react';
    import {View,StyleSheet, TouchableOpacity} from 'react-native'

const Btn= props =>{
    if(props.touch){
        return (
        <TouchableOpacity style={{...styles.boxes, ...props.style}} onPress={props.onPress}>
            {props.children}
        </TouchableOpacity>
        );
    }else{
        return (
            <View style={{...styles.boxes, ...props.style}}>
                {props.children}
            </View>
        );
    }

}
const styles= StyleSheet.create({
    boxes :{
        padding:18,
        backgroundColor:'white',
        borderRadius:20        
    }
});

export default Btn;

and in the page u want to have Btn use it like this

<Btn style={styles.items} touch="on" onPress={props.getProductsRequest}>
               <Text  style={styles.itemTxt}> some thex</Text>
        </Btn>

pay attention to the touch = on

发布评论

评论列表(0)

  1. 暂无评论