将功能绑定到React中的当前项目

时间:2018-07-18 08:31:09

标签: reactjs function find bind

如果该书在usersBooks数组中不存在,我想显示按钮以添加一本书,我认为该功能运行良好,但绑定会导致问题:

doesExistInUsersBooks = (title) => {
        if(this.props.userBooks.find(b => b.title == title)) {
            return true;
        } else {
            return false;
        }
    }

我以这种方式使用它:!this.doesExistInUserBooks.bind(this, title) && <Button ... />

3 个答案:

答案 0 :(得分:0)

声明函数后,您正在使用ES6自动绑定。这就是为什么不需要绑定。您应该尝试将代码更改为此:

!doesExistInUserBooks(title)

答案 1 :(得分:0)

您需要致电函子:

this.doesExistInUsersBooks.bind(this, title)() && <Button ... />

在此处检查其工作原理: https://stackblitz.com/edit/react-xedawq?embed=1&file=index.js

答案 2 :(得分:0)

您可以做的就是以这种方式声明您的函数:

doesExistInUsersBooks(title){
// your code
}

或如Serdar建议的那样使用它:

!doesExistInUserBooks(title)
相关问题