gpt4 book ai didi

javascript - 如何在 react 中设置单选按钮的默认值?

转载 作者:行者123 更新时间:2023-12-02 21:30:37 24 4
gpt4 key购买 nike

我有一个输入表单,我获取了 Prop ,并将它们映射为输入组件,但对于单选按钮,我无法在加载时设置默认值。有什么解决办法吗?

updateForm.jsx 现在如何根据员工 Angular 色管理员或代表选择默认单选按钮?

updateForm.jsx

const updateForm = props => {
const { sortedEmployees } = props.location.state;

const [updateFormData, handleUpdateForm] = useState({
emp_name: sortedEmployees.emp_name,
emp_phone: sortedEmployees.emp_phone,
emp_role: sortedEmployees.emp_role
});
const { emp_name, emp_phone, emp_role } = updateFormData;

const handleEmployeeForm = e => {
handleUpdateForm({ ...updateFormData, [e.target.name]: e.target.value });
};

<form className="w-full" onSubmit={e => handleUpdateEmployee(e)}>
<label className="label ml-2" htmlFor="Name">
Name
</label>
<input
className="input ml-2 mb-2"
type="text"
name="emp_name"
value={emp_name}
id="Name"
required
placeholder="Name"
onChange={e => handleEmployeeForm(e)}
/>
<label className="label ml-2" htmlFor="Phone">
Phone Number
</label>
<input
className="input ml-2 mb-2"
type="text"
pattern="[0-9]*"
name="emp_phone"
value={emp_phone}
id="Phone"
required
placeholder="Phone number"
onChange={e => handleEmployeeForm(e)}
/>
<span className="ml-2 mr-4 font-semibold">Role</span>
<label htmlFor="admin">Admin</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="admin"
id="admin"
onChange={e => handleEmployeeForm(e)}
/>
<label htmlFor="representative">Representative</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="representative"
id="representative"
onChange={e => handleEmployeeForm(e)}
/>
<button type="submit" value="submit" className="button is-primary ml-2">
Update
</button>
</form>
}

最佳答案

您应该在单选按钮上使用checked:

<label htmlFor="admin">Admin</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
checked={emp_role === 'admin'}
value="admin"
id="admin"
onChange={e => handleEmployeeForm(e)}
/>
<label htmlFor="representative">Representative</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="representative"
checked={emp_role === 'representative'}
id="representative"
onChange={e => handleEmployeeForm(e)}
/>

关于javascript - 如何在 react 中设置单选按钮的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60632791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com