我想强制设置react复选框



我想标记React js复选框组件。我想在未选中复选框时显示警告图标。我该怎么做?我分享了我在下面写的组件。

React复选框组件

const CheckBox = ({
question,
formKey,
valid = true,
validationError = 'Field is required',
}) => {
const dispatch = useDispatch()
const reduxValue = useSelector(state => state.app.forms.f3[formKey].value)
const isSaved = useSelector(state => state.app.forms.f3[formKey].saved)
const [input, setInput] = useState({
value: reduxValue,
valid: true,
})
return (
<>
<Row>
<Col className="col-1">
<label className="orange-checkbox-container">
<input
type="checkbox"
name={formKey}
onChange={(e) => changeSelected(e)}
checked={input.value}
/>
<span className="checkmark"></span>
</label>
</Col>
<Col className="col-11">
<p>{question}</p>
</Col>
</Row>
<div
className="invalid-feedback"
style={{
width: '8rem',
}}
>
{validationError}
</div>
</>
);
}

我会改进韩的回答。如果选中了复选框,则应隐藏整个div。我改进了onChange的工作方式和分离状态。使用钩子,您可以分离状态值,而不是在类中使用的方法,在类中您有1个对象this.state = {}来管理该组件的整个状态。

const CheckBox = ({
question,
formKey,
// valid = true,
validationError = 'Field is required',
}) => {
const dispatch = useDispatch();
const reduxValue = useSelector(state => state.app.forms.f3[formKey].value);
const isSaved = useSelector(state => state.app.forms.f3[formKey].saved);
const [checked, setChecked] = useState(reduxValue);
const [valid, setValid] = useState(true);
const handleCheckedChange = event => {
setChecked(event.target.checked);
}
return (
<>
<Row>
<Col className="col-1">
<label className="orange-checkbox-container">
<input
type="checkbox"
name={formKey}
onChange={handleCheckedChange}
checked={checked}
/>
<span className="checkmark"></span>
</label>
</Col>
<Col className="col-11">
<p>{question}</p>
</Col>
</Row>
{!checked &&
<div
className="invalid-feedback"
style={{
width: '8rem',
}}
>
{validationError}
</div>
}
</>
);
}

首先,您应该将validate的初始状态声明为false,并显示validationError如果input.valuefalse,我假设您的onChange正在更改input.value。

const [input, setInput] = useState({
value: reduxValue,
valid: false,
})

<div
className='invalid-feedback'
style={{
width: '8rem',
}}
>
{!input.value && validationError}
</div>

最新更新