4
关注
2174
浏览

反应添加事件监听器根据条件

为什么被折叠? 0 个回复被折叠
dreamapple 未验证用户 用户来自于: 广东省
2020-09-17 06:59
我的做法是创建一个新的道具对象newProps根据this.props是否具有所需的属性,可能会或可能不会有一个onClick财产。 在此示例中,如果Foo未收到bar prop,则它不会创建具有onClick属性的新对象。 class Foo extends Component { handleBar() { console.log(this.props.bar); } render() { const newProps = this.props.bar ? { ...this.props, onClick: this.handleBar.bind(this), } : this.props return
} } 这里有一个live example on CodePen
newbie2005 未验证用户 用户来自于: 广东省
2020-09-16 18:34

还记得绑定功能this,如果你需要引用道具/状态。我倾向于做建筑即 this.fireSomething = this.fireSomething.bind(this)

darren 未验证用户 用户来自于: 广东省
2020-09-15 19:50

怎么样:

render(){ 
    return(
     
this.fireSomething}>{name}/div> ) }

如果hasSomething连接监听器,否则onClick将收到不确定就像你不会通过任何东西。

如果上面没有你正在寻找你也可以做这样的事情的东西:

render(){ 
    const props = { 
    //... some props 
    } 

    if(hasSomething) { 
    props.onClick = this.fireSomething; 
    } 

    return(
     
{name}/div> ) }

您创建一个认为应该传递给股利和以后使用蔓延运营商的每一个道具对象通过他们。

关于作者

问题动态

发布时间
2020-09-15 15:51
更新时间
2022-09-15 16:04
关注人数
4 人关注

相关问题

个人工作笔记 Powered BY WeCenter V4.1.0 © 2024 粤ICP备2020123311号