使用React JS进行下拉的OnChange事件 [英] OnChange event using React JS for drop down
问题描述
var MySelect = React.createClass({
change: function(){
return document.querySelector('#lang').value;
},
render: function(){
return(
<div>
<select id="lang">
<option value="select" onChange={this.change}>Select</option>
<option value="Java" onChange={this.change}>Java</option>
<option value="C++" onChange={this.change}>C++</option>
</select>
<p></p>
<p value={this.change}></p>
</div>
);
}
});
React.render(<MySelect />, document.body);
onChange
事件不起作用。
推荐答案
更改事件在< select>
元素上触发,而不是< option>
元素。但是,这不是唯一的问题。您定义更改
函数的方式不会导致重新呈现组件。看起来你可能还没有完全掌握React的概念,所以也许反思中的思考 帮助。
The change event is triggered on the <select>
element, not the <option>
element. However, that's not the only problem. The way you defined the change
function won't cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe "Thinking in React" helps.
您必须将所选值存储为状态,并在值更改时更新状态。更新状态将触发组件的重新呈现。
You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.
var MySelect = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onChange={this.change} value={this.state.value}>
<option value="select">Select</option>
<option value="Java">Java</option>
<option value="C++">C++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
React.render(<MySelect />, document.body);
另请注意< p>
元素没有值
属性。 React / JSX简单地复制了众所周知的HTML语法,它没有引入自定义属性( key
和 ref $ c除外) $ C>)。如果您希望所选值为
< p>
元素的内容,则只需将其放入其中,就像使用任何静态内容一样。
Also note that <p>
elements don't have a value
attribute. React/JSX simply replicates the well-known HTML syntax, it doesn't introduce custom attributes (with the exception of key
and ref
). If you want the selected value to be the content of the <p>
element then simply put inside of it, like you would do with any static content.
了解有关事件处理,状态和表单控件的更多信息:
Learn more about event handling, state and form controls:
- http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html 一>
- http://facebook.github.io/react/docs/ forms.html
- http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html
- http://facebook.github.io/react/docs/forms.html
这篇关于使用React JS进行下拉的OnChange事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!