我已经按照这个文档创建了一个带有反应的选择标签。
我已经编辑了这个问题,如果我在选择中使用 className="browser-default" 它工作正常。但是对于实现选择它是行不通的。
onChange 事件在我的情况下不起作用。该函数没有被调用。
import React from 'react';
class Upload extends React.Component{
constructor(props){
super(props);
this.state={
degree:''
}
this.upload=this.upload.bind(this);
this.degreeChange=this.degreeChange.bind(this);
}
componentDidMount() {
$('select').material_select();
}
degreeChange(event){
this.setState({degree:event.target.value});
console.log(this.state.degree);
}
upload(){
alert(this.state.degree);
}
render() {
return (
<div className="container">
<form onSubmit={this.upload}>
<div className="input-field col s4">
<select value={this.state.degree} onChange={this.degreeChange}>
<option value="" disabled>Choose Degree</option>
<option value="B.E">B.E</option>
<option value="B.Tech">B.Tech</option>
</select>
</div>
<div className="row center-align">
<input className="waves-effect waves-light btn centre-align" type="submit" value="Submit"/>
</div>
</form>
</div>
);
}
}
我在这里没有收到任何错误,但是我的 degreeChange 函数没有被调用。我不明白我的错误是什么。
你的代码没有问题。你确定它不起作用吗?也许您假设设置状态是同步的,但实际上不是。尝试记录
target.value
。您还可以在回调中打印状态值到您的设置状态。
degreeChange(event){
console.log(`event value is ${event.target.value}`);
this.setState({degree:event.target.value}, () => {
console.log(this.state.degree);
});
}
你的确切代码的小提琴尝试改变周围的项目。你会看到状态似乎落后了。那是因为你打印状态的那一刻还没有完成它的渲染周期并且状态还没有更新。
我认为问题在于绑定方法。在您的领域中,像这样更改 onChange 属性。 onChange={this.degreeChange.bind(this)}