简体   繁体   English

React jsx 未向元素添加事件侦听器

[英]React jsx not adding event listener to the element

I have a react-redux app which requires a part which is conditional.我有一个 react-redux 应用程序,它需要一个有条件的部分。 ie it can either be a div with a certain className or a div with the same className and an onClick handler which fires an action.即它可以是具有特定 className 的 div 或具有相同 className 和触发操作的 onClick 处理程序的 div。 so I created a function which returns jsx according to the above conditions.所以我创建了一个函数,它根据上述条件返回 jsx。 Now the problem is that the onClick is not being added to the props as I expected but className is working fine.现在的问题是 onClick 没有像我预期的那样被添加到道具中,但 className 工作正常。

class someClass {
    renderSomething(){
         return <div className="someClass" onClick={() => 
    this.props.someAction()}>Something</div>
}
   render(){
        {this.renderSomething()}
   } 
}

What I expected it to be我期望它是什么

<div className="someclass" onClick={() => this.props.someAction()}>Something</div>

What Rect dev tools show Rect 开发工具显示什么

<div className="someclass">Something</div>

Don't know where I went wrong.不知道我哪里错了。

Edit 1: The function was mistakenly written outside the class.编辑1:该函数被错误地写在课外。

You have a typo.你有一个错字。 In your renderSomething() method, you should have the following:在您的renderSomething()方法中,您应该具有以下内容:

renderSomething() {
  return (
    <div className="someclass" onClick={this.props.someAction}>Something</div>
  );
}

EDIT: Now I saw that renderSomething was not a part of class from it was called from.编辑:现在我看到renderSomething不是从它被调用的类的一部分。 In order to keep reference to this , you have to move it inside of your class, hence make it class method.为了保持对this引用,您必须将其移动到您的类中,从而使其成为类方法。 If you wish to add an argument to someAction function, I suggest you add a event handler to your React component, and then assign it to a onClick.如果你想给someAction函数添加一个参数,我建议你给你的 React 组件添加一个事件处理程序,然后将它分配给一个 onClick。 Using arrow function in render method causes creation of a new function in memory every time component re-renders.在渲染方法中使用箭头函数会导致每次组件重新渲染时在内存中创建一个新函数。

Maybe you meant to do this?也许你打算这样做?

class someClass {
    renderSomething(){
        return <div className="someClass" onClick={() => this.props.someAction()}>Something</div>
    }   

    render(){
        {this.renderSomething()}
    } 
}

In your original example, renderSomething wasn't a part of someClass -- so calling this.renderSomething() would have thrown a runtime error.在你原来的例子, renderSomething不是一部分someClass -因此调用this.renderSomething()会抛出一个运行时错误。

I could be wrong, but i think我可能是错的,但我认为

render(){
     return {this.renderSomething()}
}

Is the way to go.是要走的路。 Let me know if render(){this.renderSomething()} works.让我知道render(){this.renderSomething()}有效。

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

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