反应添加事件监听器根据条件
如何将附加事件添加到jsx的基于条件的元素?下面的例子没有这样做,它只是通过一个标志到onClick函数,并没有真正附加事件。反应添加事件监听器根据条件
const { hasSomething, name } = this.props render(){ 
    return(
    <div onClick={()=>{hasSomething && this.fireSomething()}}>{name}/div> 
    ) 
} 
我可以复制2 <div>,检查是否存在hasSomething然后将其连接到一个元素,但是这是一个糟糕的重复,我为{名称}声明两次。
回答:
怎么样:
render(){     return(
     <div onClick={hasSomething && this.fireSomething}>{name}/div> 
    ) 
} 
如果hasSomething连接监听器,否则onClick将收到不确定就像你不会通过任何东西。
如果上面没有你正在寻找你也可以做这样的事情的东西:
render(){     const props = { 
    //... some props 
    } 
    if(hasSomething) { 
    props.onClick = this.fireSomething; 
    } 
    return(
     <div {...props}>{name}/div> 
    ) 
} 
您创建一个认为应该传递给股利和以后使用蔓延运营商的每一个道具对象通过他们。
回答:
还记得绑定功能this,如果你需要引用道具/状态。我倾向于做建筑即 this.fireSomething = this.fireSomething.bind(this)
回答:
我的做法是创建一个新的道具对象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 <div { ...newProps }/> 
    } 
} 
这里有一个live example on CodePen
回答:
等待,你只是想,如果满足条件调用一个方法?在这种情况下,你可以这样做:
render() {     return(
    <div onClick={() => { 
     if (hasSomething) { 
     this.fireSomething() 
     } 
    }} 
) 
} 
或
fireSomething() {     if (hasSomething) { 
    // do logic 
    } 
} 
render() { 
    return(
    <div onClick={() => this.fireSomething()} 
) 
} 
以上是 反应添加事件监听器根据条件 的全部内容, 来源链接: utcz.com/qa/266024.html



