更改所选元素的颜色 - React [英] Change color of selected element - React

查看:48
本文介绍了更改所选元素的颜色 - React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React的新手。
我正在尝试更改所选的一个特定li的颜色,而是改变所有li的颜色。

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".

当点击另一个li时,我希望第一个i再次不活动。

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

这是代码: 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')
);


推荐答案

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

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>

这篇关于更改所选元素的颜色 - React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆