更新React中单击项的属性的最佳方法

时间:2018-04-16 09:31:11

标签: javascript reactjs logic

我试图测试一个功能,如果你有一个属性为li的{​​{1}}列表,点击一个将切换到aria-checked,同时将true li's的其余部分转为aria

我在下面实现了它:

false

因此,点击后,点击的项目class Parent extends React.Component { constructor(props){ super(props); this.state = {checked: false, items:[]} this.clicky = this.clicky.bind(this); } clicky(e){ this.setState({ items: [...this.state.items, e.currentTarget] }, () => { this.state.items.map((item, index) => { if(index == this.state.items.length - 1){ item.setAttribute("aria-checked", "true"); } else{ item.setAttribute("aria-checked","false"); } }) }) } render() { return ( <ul> <li aria-checked={this.state.checked} onClick={this.clicky}>item 1</li> <li aria-checked={this.state.checked} onClick={this.clicky}>item 2</li> <li aria-checked={this.state.checked} onClick={this.clicky}>item 3</li> </ul> ) } } React.render(<Parent />, document.getElementById('app')); 将变为true,而其他所有项目将变为aria。我想知道是否有更好/更有效的方法来获得相同的结果。感谢。

工作版本:https://codepen.io/anon/pen/QmeKEw?editors=0010

2 个答案:

答案 0 :(得分:0)

有关详细信息,请参阅Intro To React

SELECT '1'
FROM   DUAL
WHERE  DATE '2018-04-11' BETWEEN SYSDATE - 14 AND SYSDATE;
// App.
class App extends React.Component {

  // State.
  state = {
    checked: false,
    items: [1, 2, 3]
  }

  // Render.
  render = () => (
    <ul>
      {this.state.items.map(item => (
        <li aria-checked={this.state.checked == item} onClick={() => this.clicky(item)}>
          Item {item}
        </li>
      ))}
    </ul>
  )
  
  // Clicky
  clicky = item => console.log('Clicked:', item) || this.setState({checked: item})
  
}

ReactDOM.render(<App/>, document.querySelector('#root'))

答案 1 :(得分:0)

您可以使用索引,设置checkedIndex状态键,并将每个项目的索引与state.checkedIndex进行比较:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { checkedIndex: -1 };
  }

 render() {
    const items = [ 'item 1', 'item 2', 'item 3' ];
    return (
      <ul>
        {items.map((item, index) =>
          <li
            key={item}
            aria-checked={this.checkedIndex === index}
            onClick={() => this.setState({ checkedIndex: index })}
          >
            item 1
          </li>)}
      </ul>
    )
  }
}

React.render(<Parent/>, document.getElementById('app'));