【问题标题】:How to set color of only the clicked IconButton - ReactJS?如何仅设置单击的 IconButton 的颜色 - ReactJS?
【发布时间】:2019-11-28 02:12:40
【问题描述】:

我是 React JS 的新手。我有多个图标按钮。 OnClick 我只希望单击的按钮更改其颜色。我使用了状态,但是当状态改变时,所有按钮的颜色都会改变。我应该采用什么方法?有没有办法在不使用状态的情况下改变颜色?需要钥匙或身份证吗? 我提供的代码被裁剪(意味着它只包含我认为相关的部分)。

class Utilitybar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bgColor: "default"
    };
  }
  render() {
    return (
      <div>
        <IconButton color={
          this.state.bgColor
        }
          onClick={
            () => {
              this.props.vidToggle();
              if (this.state.bgColor === "default") {
                this.setState({ bgColor: "primary" })
              } else {
                this.setState({ bgColor: "default" })
              }
            }
          }>
          <FaPlayCircle />
        </IconButton>
        <IconButton color={
          this.state.bgColor
        }
          onClick={
            () => {
              this.props.fileToggle();
              if (this.state.bgColor === "default") {
                this.setState({ bgColor: "primary" })
              } else {
                this.setState({ bgColor: "default" })
              }
            }
          }>
          <FaRegFileAlt />
        </IconButton>
      </div>
    );
  }
}

我希望只有点击按钮才能改变颜色。但显然它们都使用相同的状态,当状态改变时,所有按钮的颜色都会改变。

【问题讨论】:

    标签: reactjs material-ui react-component


    【解决方案1】:

    不要存储共享属性(bg 颜色),而是存储您真正需要的信息:即按下的按钮

    class Utilitybar extends React.Component {
      constructor(props) {
        super(props)
        this.onButtonClicked = this.onButtonClicked.bind(this)
        this.state = { currentButton: null }
      }
    
      onButtonClicked (id) {
        this.setState({ currentButton: this.state.currentButton === id ? null : id })
      }
    
      render(){
        return (
          <div>
            <IconButton
              color={this.state.currentButton === 0 ? "primary" : "default" }
              onClick={() => this.onButtonClicked(0)}>
              <FaPlayCircle/>
            </IconButton>
            <IconButton
              color={this.state.currentButton === 1 ? "primary" : "default" }
              onClick={() => this.onButtonClicked(1)}>
              <FaRegFileAlt/>
            </IconButton>
          </div>
        );
      }
    }
    

    编辑:这个想法是存储与您的一个按钮相对应的 ID(请注意,我假设一次只能单击一个按钮)。此 ID 置于组件状态。然后每个按钮将根据状态中的 ID 检查其 ID;如果匹配,那么它将呈现不同的背景。 由于您可能希望在第二次单击后取消按下按钮,因此 onButtonClicked 在更新状态之前会检查当前 ID,如果它与新 ID 相同,则会清除存储的 ID

    【讨论】:

    • 你能解释一下 onButtonClicked 函数的工作原理吗?
    • 如果我想一次点击多个按钮怎么办?就像,单击按钮不会清除先前单击按钮的设置颜色。我需要对代码进行哪些更改?谢谢。
    • 在状态中存储一个id数组而不是单个ID
    猜你喜欢
    • 2020-09-14
    • 2023-01-23
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    相关资源
    最近更新 更多