如何将事件函数分配给 React.js 中的 DOM 列表

How to allocate a event function to DOM list in React.js

我想问你关于在React.js中使用事件函数的问题。

我想做一个测试函数,当点击titlesList时,它会获取索引并打印索引。 但是这个功能在点击的时候不起作用

你能给我一些解决问题的建议吗?

const some = (props) = {
    // 'props' have two attributes, titles and contents
    // which each is a array of strings.



    function test(index){
        console.log('clicked');
        console.log(index);
     }

    const titlesList = props.titles.map((title, index) => {

        return <div className="eachTitle"
            key={index}
            onClick={test(index)}>
            {title} {index}
        </div>
    });

    return (
            <div>
                    {titlesList}
            </div>
    );
}

感谢您的阅读。

当您的组件被渲染时,它实际上会调用 test(index)。这会将 onClick 的值设置为 test(index) 的 return 值。您要做的是将 onClick 设置为一个函数,该函数使用适当的参数调用您想要的任何内容。

onClick={() => {test(index)}}

这是一个匿名函数,可以传递。单击时,会调用匿名函数,它实际上只是用您的参数调用 test(index)。如果您不需要向 test 传递任何参数,您可以这样做:

onClick={test}.

由于您不能告诉 onClick 传递参数(事件对象除外),匿名函数是解决该问题的简单方法。

这里的问题与绑定有关,有两种方法可以解决它,@Jtcruthers 提到的一种使用匿名函数,另一种方法是创建一个构造函数并在调用 use 时使用 .bind() 注册你的方法这个

onClick={this.test(index)}
constructor(props){
super(props);
this.test = this.test.bind(this);
}

    function test(index){
        console.log('clicked');
        console.log(index);
     }

     const titlesList = props.titles.map((title, index) => {

        return <div className="eachTitle"
            key={index}
            onClick={this.test(index)}>
            {title} {index}
        </div>
    });