Javascript 更改所选元素的颜色 - React

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42101150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:54:07  来源:igfitidea点击:

Change color of selected element - React

javascriptreactjs

提问by Polina

I'm new to React. I'm trying to change the color of one particular "li" that was selected, but instead it changes color of all "li".

我是 React 的新手。我正在尝试更改选定的一个特定“li”的颜色,但它会更改所有“li”的颜色。

Also when another "li" is clicked I want the first "i" to be not active again.

同样,当单击另一个“li”时,我希望第一个“i”不再处于活动状态。

here is the code: http://codepen.io/polinaz/pen/zNJKqO

这是代码:http: //codepen.io/polinaz/pen/zNJKqO

var List = React.createClass({
  getInitialState: function(){
    return { color: ''}
  },
  changeColor: function(){
    var newColor = this.state.color == '' ? 'blue' : '';
    this.setState({ color : newColor})
  },

  render: function () {
    return (
      <div>
        <li style={{background:this.state.color}} onClick={this.changeColor}>one</li>
         <li style={{background:this.state.color}} onClick={this.changeColor}>two</li>
         <li style={{background:this.state.color}} onClick={this.changeColor}>three</li>


      </div>
    );
  }
});
ReactDOM.render(
    <List/>,
    document.getElementById('app')
);

回答by LPL

Since you don't have any identifiers on you list items you activate/deactivate them all every time. You need to reference each of them in a different way, then you can set the color individually. This is one example

由于您在列出的项目上没有任何标识符,因此您每次都激活/停用它们。您需要以不同的方式引用它们中的每一个,然后您可以单独设置颜色。这是一个例子

var List = React.createClass({
  getInitialState: function(){
    return { active: null}
  },

  toggle: function(position){
    if (this.state.active === position) {
      this.setState({active : null})
    } else {
      this.setState({active : position})
    }
  },
  
  myColor: function(position) {
    if (this.state.active === position) {
      return "blue";
    }
    return "";
  },

  render: function () {
    return (
      <div>
        <li style={{background: this.myColor(0)}} onClick={() => {this.toggle(0)}}>one</li>
        <li style={{background: this.myColor(1)}} onClick={() => {this.toggle(1)}}>two</li>
        <li style={{background: this.myColor(2)}} onClick={() => {this.toggle(2)}}>three</li>
      </div>
    );
  }
});
ReactDOM.render(
    <List/>,
    document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
  <!-- This div's content will be managed by React. -->
</div>