如何在我的状态下使用select中的选项?
this.state = {
posts: [],
question: '',
body: '',
postType: '',
}
<select value="types" className="u-full-width">
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select> 我不确定如何根据用户的选择来设置postType的状态。
getPostType() {
const type =
this.setState({ postType: type });
}发布于 2017-10-11 09:44:47
您需要添加一个函数来处理select上的更改,保存状态中的值并将其传递给select。
如下所示:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
postType: 'Option 1',
}
this.onChange = this.onChange.bind(this)
};
onChange(event){
this.setState({
postType: event.target.value
})
}
render() {
return (
<div>
<select value={this.state.postType} onChange={this.onChange} className="u-full-width">
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
{this.state.postType}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
)<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
这称为受控组件。你可以阅读更多关于它的here。
发布于 2017-10-11 09:37:23
您可以尝试以下实现。
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
question: '',
body: '',
postType: 'Question',
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({postType: event.target.value});
}
render() {
return (
<form>
<label>
Select your postType:
<select className="u-full-width" value={this.state.postType}
onChange={this.handleChange}>
<option value="Question">Question</option>
<option value="Discussion">Discussion</option>
<option value="Clout">Clout</option>
</select>
</label>
</form>
);
}
}
ReactDOM.render(
<Sample />,
document.getElementById('root')
);发布于 2017-10-11 09:40:36
我认为您正在寻找的是以下内容:
<select className="u-full-width"
onChange= this.handleOnChange.bind(this)
ref={value => this.refName = value}>
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
handleOnchange(e){
e.preventDefault(e);
const type = this.refName.value;
setState({postType: type});
}希望能对大家有所帮助!
https://stackoverflow.com/questions/46678300
复制相似问题