首页 > 解决方案 > 如何在 React 中获取点击的元素?

问题描述

来自 jQuery,获得点击元素是轻而易举的事,但我在 React 中遇到了一些问题。基本上,我有一个列表,我想获得一个单击的列表项(或其索引)并为其设置动画。

class TodoApp extends React.Component {
  constructor(props) 
  {
    super(props)
    this.list_element = React.createRef()
    this.state = 
    {
        items: [
        { text: "Learn JavaScript", done: false },
        { text: "Learn React", done: false },
        { text: "Play around in JSFiddle", done: true },
        { text: "Build something awesome", done: true }
      ]
    }
  }
 get_index ()
 {
     console.log(this.list_element.current.children)
 }
  render() {
    return (

        <ol ref={this.list_element}>
        {this.state.items.map(item => (
          <li onClick={ () => this.get_index()}>
              <span>{item.text}</span>
          </li>
        ))}
        </ol>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

现场演示:https ://jsfiddle.net/uo1L03ng/

但是,我不知道如何在 React 中获取单击的元素。我应该改用 componentDidMount() 并使用纯 JavaScript 来获取单击的元素和未来的 DOM 操作吗?

最好的方法是什么?

标签: reactjs

解决方案


onClick映射items数组时,您可以将参数传递给处理程序。Array.prototype.map()还允许您访问元素的索引,因此,您可以将其传递给您的doSomething()方法。

这是一个CodeSandbox,可以现场试用!

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.list_element = React.createRef()
    this.state = {
      items: [
        { text: 'Learn JavaScript', done: false },
        { text: 'Learn React', done: false },
        { text: 'Play around in JSFiddle', done: true },
        { text: 'Build something awesome', done: true }
      ]
    }
  }

  doSomething(item, index) {
    console.log(item)
    console.log(index)
  }

  render() {
    return (
      <ol>
        {this.state.items.map((item, index) => (
          <li key={item.text} onClick={() => this.doSomething(item, index)}>
            <span>{item.text}</span>
          </li>
        ))}
      </ol>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector('#app'))

推荐阅读