改变单一的反应状态

时间:2016-12-02 13:42:07

标签: javascript reactjs

如何使用li将单词添加到单个onClick元素?在我点击任何li时,当div发生更改时,所有item-active都会获得state课程。

我确实有来自映射数组的index,但我不确定在哪里(我相信handleClick()?)我应该用它来使它工作......

//import {cost} from '...';
export class CostFilter extends Component {
  constructor(props) {
    super(props);

    this.state = {active: "item-not-active"};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(){
    let isActive = this.state.active === "item-not-active" ? "item-active" : "item-not-active";
    this.setState({active: isActive});
  }


  render() {
    return (
        <ul>
          {cost.map((element, index) =>
              <li onClick={this.handleClick}  value={`cost-${element.cost}`} key={index}>
                  <div className={`hs icon-${element.cost} ${this.state.active}`}></div>
              </li>
          )}
        </ul>
    );
  }
}

4 个答案:

答案 0 :(得分:3)

尝试这样的事情:

export class CostFilter extends Component {
  constructor(props) {
    super(props);
    this.state = {activeIndex: null};
  }
  handleClick(index) {
    let activeIndex = this.state.activeIndex === index ? null : index;
    this.setState({activeIndex});
  }

  render() {
    return (
      <ul>
        {cost.map((element, index) =>
          <li onClick={this.handleClick.bind(this, index)}  value={`cost-${element.cost}`} key={index}>
            <div className={`
                   hs 
                   icon-${element.cost} 
                   ${this.state.activeIndex === index && 'item-active'}
                 `}></div>
          </li>
        )}
      </ul>
    );
  }
}

答案 1 :(得分:2)

如果当前索引等于状态中的键,则可以将已单击元素的索引存储在组件的状态中,然后在map中检查渲染功能。像这样:

let data = ['Item 1', 'Item 2', "Item 3"];

class Test extends React.Component {
    constructor(){
        this.state = {
           active: null
        }
    }

    handleClick(i){ 
       this.setState({active: i});
    }

    render(){
       return <ul>{this.props.data.map((item, i) => <li key={i} className={this.state.active === i ? 'active' : ''} onClick={this.handleClick.bind(this, i)}>{item}</li>)}</ul>
    }
}

React.render(<Test data={data}/>, document.getElementById('container'));

这是fiddle

答案 2 :(得分:1)

我希望这就是你要找的东西。 https://jsfiddle.net/gusrodriguez/auuk97hf/1/

const data = ['Hello', 'World']

class Example extends React.Component {
  constructor(){
    this.state = {
        isActive: -1
    }
  }
    click(key,e){
    this.setState({
        isActive: key
    })
  }
    render(){
    const costsList = this.props.costs.map((item, key) => {
        return <li key={key} 
            className={this.state.isActive === key ? 'foo' : ''}
            onClick={this.click.bind(this, key)}>
            {item}
       </li>
    })
    return <ul>
        {costsList}
    </ul>
  }
}

React.render(<Example costs={data}/>, document.getElementById('container'));

答案 3 :(得分:0)

尝试使用React Hooks简化此操作(在codepen上查看示例)

const MyApp = (props)=>{
  const [activeIndex, setActiveIndex] = React.useState(null)

  let activeStyle = {backgroundColor:"red", width:"400px", height:"22px", margin: "2px"}
  let normalStyle = {backgroundColor:"blue", width:"400px", height:"22px", margin: "2px"}

  const handleClick = (i)=>{
    setActiveIndex(i)
  }


  let output= ["item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8", "item-9", "item-10"];


  return(
    <div>
    {output.map((v, i)=>{
        return (
          <li key={i} style={activeIndex === i ? activeStyle: normalStyle}>
            {i} : {v}
            <button onClick={()=>handleClick(i)} name={i}>Change background color</button>
          </li>)
      })}
    </div>
  )
}

enter image description here