我想在页面首次启动时获取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>
);
};
答案 0 :(得分:0)
将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>
);
};