Javascript 反应选择 onChange 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30716421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React select onChange is not working
提问by budhavarapu ranga
JsFiddle : https://jsfiddle.net/69z2wepo/9956/
JsFiddle:https://jsfiddle.net/69z2wepo/9956/
I am returning a select element in the render function in my react.jscode.
我在我的react.js代码的渲染函数中返回一个选择元素。
But whenever I change the selectvalue, the function in the onChangeis not getting triggered.
但是每当我更改select值时,中的函数onChange都不会被触发。
var Hello = React.createClass({
render: function() {
return <select id="data-type" onChange={changeDataType()}>
<option selected="selected" value="user" data-type="enum">User</option>
<option value="HQ center" data-type="text">HQ Center</option>
<option value="business unit" data-type="boolean">Business Unit</option>
<option value="note" data-type="date">Try on </option>
<option value="con" data-type="number">Con</option>
</select>
}
});
React.render(<Hello/>, document.getElementById('container'));
function changeDataType() {
console.log("entered");
}
This function is getting triggered only once when the select is loaded and subsequently when I change the value, its not getting triggered.
此功能仅在加载选择时触发一次,随后当我更改值时,它不会被触发。
回答by Crob
onChangetakes a function.
onChange需要一个函数。
You are passing it changeDataType(), which is running the function changeDataTypefunction, and setting onChangeto it's return value, which is null.
您正在传递它changeDataType(),它正在运行函数changeDataType函数,并设置onChange它的返回值,即空值。
Try passing the actual function, instead of evaluating the function.
尝试传递实际函数,而不是评估函数。
<select id="data-type" onChange={changeDataType}>
<select id="data-type" onChange={changeDataType}>
回答by Michael Parker
Functions that trigger when a component changes should really be defined inside the component itself.
当组件更改时触发的函数应该真正在组件内部定义。
I recommend defining your function inside of your Hellocomponent, and passing this.changeDataTypeto your onChangeattribute, like so:
我建议在你的Hello组件内部定义你的函数,并传递this.changeDataType给你的onChange属性,如下所示:
var Hello = React.createClass({
changeDataType: function() {
console.log('entered');
},
render: function() {
return <select id="data-type" onChange={this.changeDataType}>
<option selected="selected" value="user" data-type="enum">User</option>
<option value="HQ center" data-type="text">HQ Center</option>
<option value="business unit" data-type="boolean">Business Unit</option>
<option value="note" data-type="date">Try on </option>
<option value="con" data-type="number">Con</option>
</select>
}
});
Here is an updated JSFiddle that produces your expected behavior: https://jsfiddle.net/69z2wepo/9958/
这是一个更新的 JSFiddle,它产生您预期的行为:https://jsfiddle.net/69z2wepo/9958/

