[英]True and false radio buttons in react
這是我當前的代碼:
我組件中的狀態
this.state = {
name: '',
sample: '',
description: '',
isPublished: null,
};
這是單選按鈕的處理程序
_handleRadio(event) {
let value = true;
if (typeof event.currentTarget.value === 'string') {
(event.currentTarget.value === 'true' ? value = true : value = false );
}
this.setState({isPublished: value});
}
最后是我的單選按鈕
<div className="radio">
<label><input type="radio" name="isPublished" value="true" onChange={this._handleRadio} />Yes</label>
</div>
<div className="radio">
<label><input type="radio" name="isPublished" value="false" onChange={this._handleRadio} />No</label>
</div>
抱歉,格式化不佳,在此處復制和粘貼我的代碼效果不佳。 當我嘗試對其進行修復時,我會更加困惑。
所以現在,狀態正在改變,這正是我想要的。 但是,當我向我的api提交並發出POST請求時,isPublished狀態將返回true。
這是我的提交處理程序
_handleSubmit(event) {
event.preventDefault();
event.stopPropagation();
const sampleObj = this.state;
console.log(sampleObj);
api.post('samples', sampleObj).done((result) => {
console.log('Sample Saved!');
this.context.router.push(`${result.id}/`);
}).fail((error) => {
console.log('failed');
console.log(error);
});
}
為什么即使在將isPublished的狀態更改為false后,它在提交期間仍返回true呢?
我認為存在一些結構性問題。 沒有垃圾桶很難說,但這就是我所看到的...
首先,您將不受控制的組件與受控制的方法混合在一起。 例如,您沒有在單選按鈕上設置選中屬性(受控),但是也沒有在refs(或設置它們)上檢查值(不受控制)。 應該有一個選中的屬性進行控制。
第二,布爾值不匹配的字符串很多。 假設true和false是這些按鈕的唯一值,請嘗試:
const isPublished = event.currentTarget.value === 'true' ? true: false;
我把它放在筆上。
https://codepen.io/anon/pen/pNooXq?editors=0010
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
sample: '',
description: '',
isPublished: null,
};
this._handleRadio = this._handleRadio.bind(this);
this._handleSubmit = this._handleSubmit.bind(this);
}
_handleRadio(event) {
const isPublished = event.currentTarget.value === 'true' ? true: false;
console.log('handle', isPublished);
this.setState({ isPublished });
}
_handleSubmit(event) {
event.preventDefault();
event.stopPropagation();
const sampleObj = this.state;
console.log(sampleObj);
}
render() {
const { isPublished } = this.state;
console.log(isPublished, true);
return (
<form onSubmit={this._handleSubmit}>
<div className="radio">
<label>
<input
type="radio"
name="isPublished"
value="true"
checked={isPublished === true}
onChange={this._handleRadio} />
Yes
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
name="isPublished"
value="false"
checked={isPublished === false}
onChange={this._handleRadio} />
No
</label>
</div>
<button type="submit">Submit</button>
</form>
);
}
}
我看不到您的實際JSX,但是如果您希望它們反映當前狀態,則需要在相應的單選按鈕中設置選中屬性。
因此,類似:
checked={this.state.isPublished === true}
對於第一個單選按鈕;
checked={this.state.isPublished === false}
第二。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.