Javascript 根据条件添加事件侦听器

Javascript 根据条件添加事件侦听器,javascript,reactjs,Javascript,Reactjs,如何根据条件将附加事件添加到jsx的元素中?下面的示例没有这样做,它只是将一个标志传递到onClick函数中,并没有真正附加事件 const { hasSomething, name } = this.props render(){ return( <div onClick={()=>{hasSomething && this.fireSomething()}}>{name}/div> ) } const{hasSomethi

如何根据条件将附加事件添加到jsx的元素中?下面的示例没有这样做,它只是将一个标志传递到onClick函数中,并没有真正附加事件

const { hasSomething, name } = this.props 

render(){
   return(
     <div onClick={()=>{hasSomething && this.fireSomething()}}>{name}/div> 
   )
}
const{hasSomething,name}=this.props
render(){
返回(
{hasSomething&&this.fireSomething()}}>{name}/div>
)
}
我可以复制2
,检查是否存在
hasSomething
,然后将其附加到其中一个元素,但这对我来说是一个糟糕的复制,因为{name}声明了两次。

如何:

render(){
   return(
      <div onClick={hasSomething && this.fireSomething}>{name}/div> 
   )
} 

创建一个对象,该对象保存应传递给div的每个道具,然后使用spread运算符传递它们。

如果需要引用道具/状态,请记住将函数绑定到该。我倾向于在建筑中这样做。
this.fireSomething=this.fireSomething.bind(this)
我的方法是创建一个新的props对象
newProps
,根据
this.props
是否具有所需的属性,该对象可能具有或不具有
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 }/>
  }
}
在本例中,如果
Foo
没有收到
bar
属性,它将不会使用
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 }/>
  }
}
类Foo扩展组件{
车把{
console.log(this.props.bar);
}
render(){
const newProps=this.props.bar
? {
…这是道具,
点击:这个。把手。绑定(这个),
}
:这是道具
返回
}
}

这里有一个

等待,如果满足条件,您只想调用一个方法?在这种情况下,您可以这样做:

render() {
  return(
    <div onClick={() => {
      if (hasSomething) {
        this.fireSomething()
      }
    }}
  )
}
render(){
返回(
{
如果(hasSomething){
这个
}
}}
)
}

fireSomething(){
如果(hasSomething){
//做逻辑
}
}
render(){
返回(
this.fireSomething()}
)
}

我认为您的逻辑没有任何问题。例如,您还可以准备道具(基于不同的条件),并在
render()
中的渲染标记中使用spread
操作符传递道具变量/对象。e、 g.
您仍然有onClick附件。@JennyMok我在答案中加入了另一个示例。也许这就是你想要的。不,我使用了箭头函数,没有必要像你说的那样绑定。
fireSomething() {
  if (hasSomething) {
    // do logic
  }
}

render() {
  return(
    <div onClick={() => this.fireSomething()}
  )
}