快速起草了一份草案,可能不是最好的解决方案,但希望它有助于后面的逻辑。
您可以将单选按钮的状态存储在组件的状态中:
state = {
genderRadioClicked: false,
ageRadioClicked: false
// Add any extra group you create later
}
并使用来自
输入
使用
设置状态
。
验证方法如下所示:
_handleRadioValidation = (e) => {
// Get the state of all the radio buttons
const radioStates = this.state
// Iterate through the radio state object and return the value for
// every key and assign it to an array
const checkedStatus = Object.keys(radioStates).map((key) => {
return radioStates[key];
});
// Once you got the array with the value of the group radios (if
// the group is checked or not) filter the array to return only if the
// value is equal to false (which means that it's not checked)
const filteredArray = checkedStatus.filter((value) => value === false)
// If the length of the resulting array from the filtering is bigger
// than 0 it means one of the group is false (unchecked)
// Then you just prevent the default behaviour of the event, in this
// case that is a link, it will disable the link.
if (filteredArray.length > 0) {
e.preventDefault();
return;
}
// If all of them are checked it will execute like normal
}
最后,将此方法附加到组件,如下所示:
<Link to="/" onClick={(e) => this._handleRadioValidation(e)}>
希望有帮助!