简体   繁体   English

如何在 React.js 中将事件 function 分配给 DOM 列表

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

I would like to ask you about using a event function in React.js.我想问你关于在 React.js 中使用事件 function 的问题。

I want to make test function, which would get index and print index when of titlesList is clicked.我想测试 function,当点击titlesList 时会得到索引和打印索引。 But this function doesn't work when is clicked.但是这个 function 在点击时不起作用。

Could you give me advices to solve it?你能给我建议来解决它吗?

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>
    );
}

Thank you for reading.感谢您的阅读。

When your component is rendered, it will actually call test(index) .当你的组件被渲染时,它实际上会调用test(index) This sets the value of onClick to the return value of test(index) .onClick的值设置为test(index)的返回值。 What you'll want to do is set onClick to a function that calls whatever you want with the proper arguments.您要做的是将 onClick 设置为 function ,使用适当的 arguments 调用您想要的任何内容。

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

This is an anonymous function, which can be passed around.这是一个匿名的function,可以四处传递。 When clicked, the anonymous function is called, which really just calls test(index) with your arguments.单击时,会调用匿名 function,它实际上只是使用您的 arguments 调用test(index) If you didn't need to pass any argument to test , you could have just done:如果您不需要将任何参数传递给test ,您可以这样做:

onClick={test} . onClick={test}

Since you can't tell onClick to pass arguments (besides the event object), the anonymous function is an easy way to get around that.由于您不能告诉 onClick 传递 arguments (除了事件对象),匿名 function 是解决这个问题的简单方法。

The problem here is with the binding, there are two approach to resolve it, one mentioned by @Jtcruthers using anonymous function and another way is to create a constructor and register you method using .bind() while calling use this这里的问题在于绑定,有两种解决方法,@Jtcruthers 使用匿名 function 提到的一种方法是创建一个构造函数并在调用时使用.bind()注册您的方法 use this

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>
    });


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM