onclick 不触发反应 [英] onclick not firing in react
问题描述
我对反应很陌生,我坚持了一些想法.我遇到的问题是 onclick 没有启动.
class Application 扩展 React.Component{使成为 () {返回 (<div><button onClick={alert("hello world")}>Hello Application</button>
)}}ReactDOM.render(
我期待当按钮被点击时,提示说 hello world 将出现.然而,这并没有发生!这是为什么?
您在将 alert()
分配给按钮的 onClick
事件时调用了它.
尝试将其包装在 es6 箭头函数中.
或者更好..使它成为组件上的方法,作为处理程序传递给按钮,如下所示:
class Application 扩展 React.Component {构造函数(道具){超级(道具);//因为你在回调中使用这个方法,不要忘记//绑定 this 上下文this.handleClick = this.handleClick.bind( this );}句柄点击(){警报(你好世界");}使成为(){返回(<div><button onClick={ this.handleClick }>Hello Application</button>
);}}
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屋!