繁体   English   中英

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

[英]Binding function to current item in React

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

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

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

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

!doesExistInUserBooks(title)

您需要致电函子:

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

检查它是否正常工作: https : //stackblitz.com/edit/react-xedawq?embed=1&file=index.js

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

doesExistInUsersBooks(title){
// your code
}

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

!doesExistInUserBooks(title)

暂无
暂无

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

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