【问题标题】:onclick not firing in reactonclick没有在反应中触发
【发布时间】:2017-07-21 21:26:17
【问题描述】:

我对反应很陌生,我坚持了一些想法。我遇到的问题是 onclick 没有启动。

class Application extends React.Component{
    render () {
        return (
            <div>
                <button onClick={alert("hello world")}>Hello Application</button>
            </div>
        )
    }  
}

ReactDOM.render(<Application />,document.getElementById("tar"));

我期待当点击按钮时,会出现警告说你好世界。然而,这并没有发生!这是为什么呢?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您在将alert() 分配给按钮的onClick 事件时调用它。

    尝试将其包装在 es6 箭头函数中。

    &lt;button onClick={() =&gt; { alert("hello world")} }&gt;Hello Application&lt;/button&gt;

    或者更好..使它成为组件上的一个方法,作为处理程序传递给按钮,如下所示:

    class Application extends React.Component {
        constructor( props ) {
            super( props );
    
            // since you're using this method in a callback, don't forget to
            // bind the this context
            this.handleClick = this.handleClick.bind( this );
        }
    
        handleClick() {
            alert( "hello world" );
        }
    
        render(){
            return(
                <div>
                    <button onClick={ this.handleClick }>Hello Application</button>
    
                    </div>
            );
        }
    }
    

    【讨论】:

      【解决方案2】:

      onClick 将运行提供给它的函数。如果你愿意的话

       onClick={() => alert("hello world")} /** es6 **/
      

      onClick={function() { alert("hello world"); }}
      

      【讨论】:

        【解决方案3】:

        需要绑定onclick按钮

        class Application extends React.Component{
        render(){
            return(
              <div>
                <button onClick={() => alert("hello world")}>Hello Application</button>
              </div>
            )
          }  
        }
        
        ReactDOM.render(<Application />,document.getElementById("tar"));
        

        【讨论】:

          【解决方案4】:

          因为您将警报作为对象而不是作为要完成的方法,所以您需要将警报包装在类的函数或方法中。 试试这个代码:

          class Application extends React.Component{
           render(){
            return(
              <div>
               <button onClick={() => alert("hello world")}>Hello Application</button>
          
            </div>
          
            )
           }  
          
          }
          
          ReactDOM.render(<Application />,document.getElementById("tar"));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-02-19
            • 2017-07-07
            • 2018-10-18
            相关资源
            最近更新 更多