问题描述
已经阅读了React文档并将问题归结为一个简单的案例,但仍然不太了解我在做什么错.
Have read through the React docs and boiled the problem down to a simple case, still can't quite understand what I'm doing wrong.
JSFiddle: https://jsfiddle.net/justin_levinson/pyn7fLq5/或编写如下:
JSFiddle: https://jsfiddle.net/justin_levinson/pyn7fLq5/ or written below:
var TestForm = React.createClass({
render : function() {
return (
<div>
<p>Test Form</p>
<form>
<TestBox />
</form>
</div>
)
}
});
var TestBox = React.createClass({
render : function() {
return (<input type="checkbox" name={"testbox"} defaultChecked={true} onChange={this.handleCheck()}/>)
},
handleCheck : function(event) {
console.log("check");
console.log(event);
}
});
页面加载后,我在日志中得到一个检查",随后是该事件的未定义",然后在随后的点击中它不会再次触发.尝试过使用onClick和onChange进行此操作,还创建了一个受控的(checked = {true})而不是上面的不受控制的(defaultChecked = {true}).
When the page loads, I get a 'check' in the log followed by 'undefined' for the event, then it doesn't fire again on subsequent clicks. Have tried this with both onClick and onChange as well as creating a controlled (checked={true}) instead of the uncontrolled (defaultChecked={true}) above.
谢谢!
推荐答案
因为您已经在render上调用了该方法.
Because you're already calling the method on render.
将 onChange = {this.handleCheck()}
更改为 onChange = {this.handleCheck}
这篇关于为什么我的React复选框onChange处理程序在渲染时触发,然后在单击该框时不触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!