onclick 不触发反应 [英] onclick not firing in react

查看:50
本文介绍了onclick 不触发反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

class Application 扩展 React.Component{使成为 () {返回 (<div><button onClick={alert("hello world")}>Hello Application</button>

)}}ReactDOM.render(,document.getElementById("tar"));

我期待当按钮被点击时,提示说 hello world 将出现.然而,这并没有发生!这是为什么?

解决方案

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

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

);}}

I am very new to react and I stuck on some idea. The problem I have is that onclick is not firing up.

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

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

I am expecting when the button is clicked, alert saying hello world will be show up. However, that is not happening! Why is that?

解决方案

You are invoking the alert() when assigning it to the onClick event of the button.

Try wrapping it in an es6 arrow function.

<button onClick={() => { alert("hello world")} }>Hello Application</button>

Or better still.. make it a method on the component that you pass as the handler to the button like this:

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>
        );
    }
}

这篇关于onclick 不触发反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆