Javascript ReactJS:从没有onChange事件的道具中选择默认值?
所以,我只是想知道我是否真的需要在React中的select组件上有一个onChange事件处理程序 我有一个道具在我想要选择的选项上传递默认值。如果我有:Javascript ReactJS:从没有onChange事件的道具中选择默认值?,javascript,reactjs,Javascript,Reactjs,所以,我只是想知道我是否真的需要在React中的select组件上有一个onChange事件处理程序 我有一个道具在我想要选择的选项上传递默认值。如果我有: <select value={this.props.defaultValue} > <option value="a">A</option> <option value="b">B</option> </select> 当我使用Jquery获取值时,我不
<select
value={this.props.defaultValue}
>
<option value="a">A</option>
<option value="b">B</option>
</select>
当我使用Jquery获取值时,我不需要状态或子级和父级之间的任何传递
有没有一种简单的方法可以让select从props中获取默认值,并且仍然像普通的select一样操作,其中更改一个选项会更改我可以用jquery获取的值,或者我必须有一个状态和一个onChange处理程序
谢谢
我已经尝试过的:
<select
defaultValue={this.props.defaultValue} // just returns the first option
>
<options etc.>
</select>
另外,我不希望使用像React Select这样的外部包。。。我只想要一个默认值和一个普通选择…您可以试试
您不需要为状态更新编写事件处理程序,DOM将处理它,
然后您可以使用ref从DOM中获取表单值,正如@julien所提到的,您可以使用ref而不是JQuery来获取非受控组件中select的当前值:
class MySelect extends React.Component {
constructor(props) {
super(props);
this.state = { currentValue: this.props.defaultValue };
}
updateValue() {
this.setState({ currentValue: this.refs.myselect.value });
}
render () {
return (
<div>
<div>
<button className="current" onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button>
</div>
<select ref="myselect" defaultValue={this.props.defaultValue}>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
);
}
}
类MySelect扩展了React.Component{
建造师(道具){
超级(道具);
this.state={currentValue:this.props.defaultValue};
}
updateValue(){
this.setState({currentValue:this.refs.myselect.value});
}
渲染(){
返回(
{this.state.currentValue}
A.
B
C
);
}
}
对于另一部分,defaultValue
应该像您尝试的那样工作
检查此示例fiddle:您使用的是什么版本的react?您所做的是有效的,可能会更新您的react版本,请检查以下内容:
class MySelect extends React.Component {
constructor(props) {
super(props);
this.state = { currentValue: this.props.defaultValue };
}
updateValue() {
this.setState({ currentValue: this.refs.myselect.value });
}
render () {
return (
<div>
<div>
<button className="current" onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button>
</div>
<select ref="myselect" defaultValue={this.props.defaultValue}>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
);
}
}