我正在尝试重置单选按钮,在添加一些表单数据之后,但它发生了反应。
在add方法中,我试图将单选按钮的状态值设置为空白。
我尝试了不同的方法使单选按钮再次变为空白。其中没有一个正在工作
我看到一些反应js单选按钮逻辑。
export class AddColumns extends React.Component{
constructor(props) {
super(props);
this.state={
newItemInput: '',
selectedDataValue: '',
buyItems :['Development','Testing']
}
}
handleChangeData = (event) => {
this.setState({
...this.state,
selectedDataValue: event.target.value
});
};
change (event){
this.setState({
[event.target.name]:event.target.value
});
console.log("button clicked",this.state);
};
addColumnItem(e) {
e.preventDefault();
const newItemInput = this.state.newItemInput;
var newRadioDataValue = this.state.selectedDataValue;
//doing adding stuff, then reseting all fields
this.setState({
newItemInput : '',
newRadioDataValue: '', //but this radio button is not reseting
})
}
render(){
return(
<div className="container">
<form id="Form" className="form-horizontal" onSubmit={(e) => { this.addColumnItem(e) }}>
<div className="form-group">
<label className="sr-only" htmlFor="newItemInput">Add New Item</label>
<input type ="text" ref ={input => this.newColumn = input} name="newItemInput" placeholder="Modules" value = {this.state.newItemInput} className="form-control"
id="newItemInput" onChange={event => this.change(event)}/>
</div>
<div className="form-group">
<label className="control-label col-sm-3">Data Type:</label>
<div className="col-sm-5">
<label className="radio-inline pull-left">
<input type="radio" name="radioData" value="InputData" onChange={this.handleChangeData} />Input Data
</label>
<label className="radio-inline pull-left">
<input type="radio" name="radioData" value="TargetData" onChange={this.handleChangeData} />Target Data
</label>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Add</button><p>{this.state.messgae}</p>
</div>
</form>
</div>
);
}
答案 0 :(得分:0)
您应该在setState
:this.setState({ selectedDataValue: '' })
中使用相同的密钥。
此外,您只需在setState
中指定更改的密钥:
this.setState({
...this.state, // this line can be removed
selectedDataValue: event.target.value
});
修改强>
如果要清除收音机选择,可以添加checked
道具:
state = { ..., radioChecked: false };
...
<input
type="radio"
checked={this.state.radioChecked}
onClick={() => this.setState({ radioChecked: true })}
/>
...
this.setState({ radioChecked: false }); // to clear it