我对反应很陌生,并且坚持了一些想法。我遇到的问题是 onclick 没有启动。
class Application extends React.Component{
render () {
return (
<div>
<button onClick={alert("hello world")}>Hello Application</button>
</div>
)
}
}
ReactDOM.render(<Application />,document.getElementById("tar"));
Run Code Online (Sandbox Code Playgroud)
我期待当单击按钮时,会显示“hello world”警报。然而,这并没有发生!这是为什么?
alert()您在将其分配给onClick按钮事件时调用。
尝试将其包装在 es6 箭头函数中。
<button onClick={() => { alert("hello world")} }>Hello Application</button>
或者更好的是......将其作为组件上的方法作为处理程序传递给按钮,如下所示:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17426 次 |
| 最近记录: |