如何通过单选中的selectButton获取值

问题描述 投票:0回答:1

嗨,我有这个渲染方法

return(
                            <Form.Group className={'d-flex  justify-content-start'}>
                                <Form.Label className={'mb-0 mr-2'}><b>Pohlavie:</b></Form.Label>
                                <Form.Check
                                    type="radio"
                                    label="Muž"
                                    name="formHorizontalRadios"
                                    id="formHorizontalRadios1"
                                    className={'mr-2'}
                                />
                                <Form.Check
                                    type="radio"
                                    label="Žena"
                                    name="formHorizontalRadios"
                                    id="formHorizontalRadios2"
                                />
                            </Form.Group>
)

我正在使用react bootstrap Form。检查单选类型组件。现在,从父母那里,我正在通过具有user.gender属性(1或0)的道具获得对象,我该如何通过状态或某物将这个radioselect与性别属性连接起来?就像我选择女孩时一样,我必须将user.gender更改为1,而且我还必须使这些radioselects之一默认检查user.gender的值是否不为null ...我该怎么做?

javascript reactjs react-bootstrap
1个回答
1
投票
您需要将单选按钮的onChange附加到将修改您的状态的回调中:

const { useState } = React, { render } = ReactDOM, { Form } = ReactBootstrap, rootNode = document.getElementById('root') const App = () => { const [gender, setGender] = useState() return ( <Form.Group className={'d-flex justify-content-start'}> <Form.Label className={'mb-0 mr-2'}><b>Pohlavie:</b>{gender && `(${gender})`}</Form.Label> <Form.Check type="radio" label="Muž" name="formHorizontalRadios" id="formHorizontalRadios1" className={'mr-2'} onChange={() => setGender('male')} /> <Form.Check type="radio" label="Žena" name="formHorizontalRadios" id="formHorizontalRadios2" onChange={() => setGender('female')} /> </Form.Group> ) } render ( <App />, rootNode )
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"></script><div id="root"></div>
© www.soinside.com 2019 - 2024. All rights reserved.