reactjs - 如何在 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 操作吗?
最好的方法是什么?
解决方案
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'))
推荐阅读
- javascript - 无法访问 vuejs 中的 dom 元素
- javascript - 为什么 npm 不启动?
- javascript - 访问json对象时Javascipt打印未定义
- python - 故障图像有哪些我可以检测到的特征?
- python-sphinx - 是否可以在我的文档中包含外部 rst 文件?
- python - 使用字典在数据框的文本列中搜索关键字
- mysql - 行计数超过一千并且文件大小确认
- javascript - discord.js 异步函数捕获未触发
- javascript - 如何在屏幕javascript上获取数字输入
- python - 为什么我的蜘蛛提取的物品数量有限