React中如何将单选框的字符串值转换为布尔值用于请求分发
I totally get your frustration here—using Boolean() on non-empty strings like "0" will always return true, which isn't what you want. Let's go through a few solid ways to get actual boolean values from those radio buttons:
1. Convert the value directly in your handleChange function
This is my go-to approach because it keeps your state clean from the start. Modify your handleChange utility to check if the field is isItAvailable, then convert the string value to a boolean:
const handleChange = (fieldName) => (e) => { let value = e.target.value; // Convert "1"/"0" to true/false specifically for this field if (fieldName === 'isItAvailable') { value = e.target.value === '1'; } // Update your inputs state as usual setInputs(prevState => ({ ...prevState, [fieldName]: value })); };
Now whenever the radio button is toggled, your inputs.isItAvailable will be a boolean (true for "Yes", false for "No") right away.
2. Convert the value when submitting the form
If you only need the boolean for the API request and don't mind keeping the string in state until then, handle the conversion in your submit handler:
const handleSubmit = (e) => { e.preventDefault(); // Format the inputs for your request const requestData = { ...inputs, isItAvailable: inputs.isItAvailable === '1' }; // Send your request with requestData fetch('/your-api-endpoint', { method: 'POST', body: JSON.stringify(requestData), // ... other options like headers }); };
3. Control the radio buttons with boolean state directly
You can skip the string values entirely by using the checked prop to tie each radio button to your boolean state:
<Form.Group className="radio"> <Form.Label className="radio-subtitle"> Is it operable?{" "} </Form.Label> <div className="radio-check"> <Form.Check type="radio" label="Yes" id="op-yes" name="isItAvailable" checked={inputs.isItAvailable === true} onChange={() => setInputs(prev => ({...prev, isItAvailable: true}))} /> <Form.Check type="radio" label="No" id="op-no" name="isItAvailable" checked={inputs.isItAvailable === false} onChange={() => setInputs(prev => ({...prev, isItAvailable: false}))} /> </div> </Form.Group>
This way, your inputs.isItAvailable is always a boolean from the moment the component loads—just make sure to initialize it to false or true in your state!
All three methods will solve your problem—pick the one that fits how you're managing state and form submission best!
内容的提问来源于stack exchange,提问作者user6517334

