问题
I am trying to write a radio button group using Semantic UI in React. I can get the Radio Group example on the Radio page of the Semantic UI to work. It is written by extending Component
. I want to write the same thing defining React components as functions instead of classes and using the state hook. I can't get this to work.
I modified the example to look like this.
import React, {useState} from 'react'
import {Form, Radio} from 'semantic-ui-react'
export const RadioExampleRadioGroup = () => {
const [value, setValue] = useState({});
const handleChange = event => setValue({value: event.target.value});
return (
<Form>
<Form.Field>
Selected value: <b>{value.value}</b>
</Form.Field>
<Form.Field>
<Radio
label='Choose this'
name='radioGroup'
value='this'
checked={value.value === 'this'}
onChange={handleChange}
/>
</Form.Field>
<Form.Field>
<Radio
label='Or that'
name='radioGroup'
value='that'
checked={value.value === 'that'}
onChange={handleChange}
/>
</Form.Field>
</Form>
)
};
Nothing happens in the UI when I click on the radio buttons.
Running in the debugger I see that handleChange
is getting called and appears to be doing the right thing, but it looks like undefined
is passed to the checked
functions.
What am I doing wrong here?
回答1:
I tried Semantic UI on Codesandbox and found that event.target.value
- is undefined, because target
- is a label
element, not input
, so you need to change
const handleChange = event => setValue({value: event.target.value});
to
const handleChange = (event, {value}) => setValue({ value });
like documentation of Semantic UI says
And one more advice. If you need to store just one radio button value, you don't need to store it in the object, so you could rewrite your code to:
export const RadioExampleRadioGroup = () => {
const [value, setValue] = useState(null);
const handleChange = (event, {value}) => setValue(value);
return (
<Form>
<Form.Field>
Selected value: <b>{value}</b>
</Form.Field>
<Form.Field>
<Radio
label='Choose this'
name='radioGroup'
value='this'
checked={value === 'this'}
onChange={handleChange}
/>
</Form.Field>
<Form.Field>
<Radio
label='Or that'
name='radioGroup'
value='that'
checked={value === 'that'}
onChange={handleChange}
/>
</Form.Field>
</Form>
)
};
来源:https://stackoverflow.com/questions/58735268/how-do-i-write-a-semantic-ui-radio-group-in-react-using-the-state-hook