2016-04-21 48 views
0
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> 
    ); 
    } 
}); 

回答

1

的問題是在這裏我想:onClick={this.handleDropDown(monthSelections[month])你不能給參數回調的方式。你可以試試這個:

onClick={this.handleDropDown.bind(null, monthSelections[month])}

+0

「TypeError:無法讀取null的屬性'DropdownSelected'」 – topazt

+0

因爲您的'DropDown'組件中沒有'state'屬性。你可以閱讀關於'React'組件如何工作[這裏](https://facebook.github.io/react/docs/tutorial.html)和[這裏](https://facebook.github.io/react/docs /thinking-in-react.html)。 – sehrob

+0

作爲一個解決方法,你可以把 'getInitialState(){ 回報{ DropdownSelected:monthSelections [ 「04」] } }, handleDropDown(X){ this.setState({DropdownSelected:X}) ; }' 到您的'DropDown'組件 – sehrob