试图设置下拉值
问题描述:
var monthSelections = {
"01": "January",
"02": "February",
"03":"March",
"04":"April",
"05": "May",
"06":"June",
"07":"July",
"08":"August",
"09":"September",
"10": "October",
"11":"November",
"12": "December",
"": "full year"
};
的状态和代码:试图设置下拉值
getInitialState(){
return {
DropdownSelected: monthSelections["04"]
}
},
handleDropDown(x){
this.setState({DropdownSelected:x });
}
DropDown = React.createClass({
render() {
return(
<div className="dropdown ">
<button className="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
{this.state.DropdownSelected}
<span className="caret"></span>
</button>
<ul className="dropdown-menu" aria-labelledby="dropdownMenu1" value={this.state.DropdownSelected}>
{Object.keys(monthSelections).map(function(month){
return (
<li ><a href="#" onClick={this.handleDropDown(monthSelections[month]) }> {monthSelections[month]} </a></li>
);
}.bind(this))
}
</ul>
</div>
);
}
});
答
的问题是在这里我想:onClick={this.handleDropDown(monthSelections[month])
你不能给参数回调的方式。你可以试试这个:
onClick={this.handleDropDown.bind(null, monthSelections[month])}
。
“TypeError:无法读取null的属性'DropdownSelected'” – topazt
因为您的'DropDown'组件中没有'state'属性。你可以阅读关于'React'组件如何工作[这里](https://facebook.github.io/react/docs/tutorial.html)和[这里](https://facebook.github.io/react/docs /thinking-in-react.html)。 – sehrob
作为一个解决方法,你可以把 'getInitialState(){ 回报{ DropdownSelected:monthSelections [ “04”] } }, handleDropDown(X){ this.setState({DropdownSelected:X}) ; }' 到您的'DropDown'组件 – sehrob