我是React的新手,我已经为单选按钮编写了一个代码,但是它不能正常工作,我想选择一个默认选中,但是这也不行,点击也无法选择任何按钮。请帮助我,并提前致谢
var FlightDetails = React.createClass({
getInitialState:function () {
return {
view :'fare',
selectedOption :0
};
},
handleChange: function (e) {
if(e.target.value == 'itinerary'){
this.setState({
view: 'itinerary',
selectedOption :1
})
}
if(e.target.value == 'fare'){
this.setState({
view: 'fare',
selectedOption :0
})
}
},
render:function () {
return(
<div id={this.props.id} className="collapse flightDetails">
<div className="row col-sm-12 col-centered">
<label className="col-sm-3 col-xs-12 col-sm-3 col-sm-3">
<input type="radio" name="Details" value={'fare'}
checked={this.state.selectedOption == 0}
onChange={this.handleChange}/>{' '}Fare
</label>
<label className="col-sm-3 col-xs-12 col-sm-3 col-sm-3">
<input type="radio" name="Details" value={'itinerary'}
checked={this.state.selectedOption == 1}
onChange={this.handleChange}/> {' '}Itinerary
</label>
</div>
</div>
)
}
});
这是jsfiddle。
答案 0 :(得分:0)
如果我很了解你想要的东西,你可以这样:
var FlightDetails = React.createClass({
getInitialState:function () {
return {
view :'fare',
selectedOption: false
};
},
handleChange: function (e) {
if(e.target.name == 'itinerary'){
this.setState({
view: 'itinerary',
selectedOption: true
})
}
if(e.target.name == 'fare'){
this.setState({
view: 'fare',
selectedOption: false
})
}
},
render:function () {
return(
<div id={this.props.id} className="collapse flightDetails">
<div className="row col-sm-12 col-centered">
<label className="col-sm-3 col-xs-12 col-sm-3 col-sm-3">
<input type="radio" name="fare"
checked={!this.state.selectedOption}
onChange={this.handleChange.bind(this)}/>{' '}Fare
</label>
<label className="col-sm-3 col-xs-12 col-sm-3 col-sm-3">
<input type="radio" name="itinerary"
checked={this.state.selectedOption}
onChange={this.handleChange.bind(this)}/> {' '}Itinerary
</label>
</div>
</div>
)
}
});
这是jsfiddle。