激活材质用户界面按钮时的颜色

时间:2020-05-19 19:58:43

标签: javascript reactjs jsx

Before the button click After the button click 我正在尝试单击材质用户界面按钮的颜色。 我有多个按钮。当我单击一个按钮时,所有它们的颜色会同时更改。我如何只更改被单击的那个。我有以下代码,但它没有做工作,应该做。

   constructor(props){
      super(props);
      this.state={
      videos : data,
      filtered: data,
      color : "primary"
    };
   }

   handleClick = (event) => {
    const value = event.currentTarget.value;
    console.log(event);
    this.setState({
      filtered: this.state.videos.filter(item => { 
          return item.category === value
      }),
      color: "secondary"
    });
  }

  <Button value="java" onClick={this.handleClick} variant="contained" 
   color={this.state.color} >java</Button> 
  <Button value="React" onClick={this.handleClick} 
   variant="contained" color={this.state.color}>React</Button> 
  <Button value="C#" onClick={this.handleClick}  
   variant="contained" color={this.state.color}>C#</Button> 

3 个答案:

答案 0 :(得分:0)

状态更改似乎不在传递给setState()的对象中,应该是:

this.setState({
    filtered: this.state.videos.filter(item => { 
        return item.category === value
    }),
    Color: "secondary"
});

答案 1 :(得分:0)

    handleClick = (event) => {
        const value = event.currentTarget.value;
        this.setState({ filtered: this.state.videos.filter(item => { 
                return item.category === value
            }), {Color: "secondary"}
        })
   }

您刚刚在过滤器的回调函数中插入了颜色, 只需更改即可使用

答案 2 :(得分:0)

请检查以下示例:

import React, {useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

export default function ContainedButtons() {
    const [color, setColor] = useState('primary');

    return (
        <div>
            <Button variant="contained" color={color} onClick={() => {setColor('secondary')}}>
                Click Me
            </Button>
        </div>
    );
}