我想在页面首次启动时获取 RadioButton 属性(例如:第一次调用 componentWillMount((时(我将这个问题与JQuery进行比较。
$(function() {
var radioAttr = $('#radioButton_id').find("option:selected").val()
});
我想将 JQuery 源代码实现到 React Hooks。 如果你知道如何,请帮助我..
const UserEdit = ({ classes, ...props }) => {
const types = [
{id:'INDIVIDUAL'},
{id:'COMPANY'}
];
const [ checked, setChecked ] = useState(true);
const onClickRadioBtn = (event,id) => {
(id === "COMPANY") ? setChecked(false) : setChecked(true)
};
useEffect(()=>{
**/* get radioButton attr */**
});
return(
<Edit {...props}>
<SimpleForm>
<TextInput source="username" validate={required()}/>
<TextInput source="email" validate={[required(),email()]}/>
<TextInput source="phoneNumber" validate={[required(),minLength(10),number()]}/>
<RadioButtonGroupInput label="Type"
source="userType"
choices={types}
optionText="id"
validate={required()}
onChange={onClickRadioBtn}
/>
{ !checked && (
<ReferenceInput label="Company" source="company.id" reference="companies" validate={required()}>
<SelectInput optionText="name"/>
</ReferenceInput>
)}
</SimpleForm>
</Edit>
);
};
将RadioButtonGroupInput
包裹在div
中,并为该div
提供一个ref
道具。我们还将创建一个名为 nodes
的新变量来存储元素
const UserEdit = ({ classes, ...props }) => {
const nodes = {}
const types = [
{id:'INDIVIDUAL'},
{id:'COMPANY'}
];
const [ checked, setChecked ] = useState(true);
const onClickRadioBtn = (event,id) => {
(id === "COMPANY") ? setChecked(false) : setChecked(true)
};
useEffect(()=>{
//get the element we passed, our input will be the first child
let input = nodes.example.children[0] ? nodes.example.children[0] : null;
console.log(input.getAttribute("type"));
}, []);
return(
<Edit {...props}>
<SimpleForm>
<TextInput source="username" validate={required()}/>
<TextInput source="email" validate={[required(),email()]}/>
<TextInput source="phoneNumber" validate={[required(),minLength(10),number()]}/>
<div ref={elem => (nodes["example"] = elem)}>
<RadioButtonGroupInput label="Type"
source="userType"
choices={types}
optionText="id"
validate={required()}
onChange={onClickRadioBtn}
/>
</div>
{ !checked && (
<ReferenceInput label="Company" source="company.id" reference="companies" validate={required()}>
<SelectInput optionText="name"/>
</ReferenceInput>
)}
</SimpleForm>
</Edit>
);
};
例如,这是一个沙盒:https://codesandbox.io/s/romantic-mcnulty-qqpbs