我创建了一个自定义单选按钮组件,我正在导入它并将其映射到一个数组。 如果我点击单选按钮,它不会在第一次点击时选择值,但在第二次点击后它开始选择值
传递名称id值并通过道具检查
const CustomRadioButton = (props: any) => {
const { label, id, name, onChange,isChecked } = props;
return (
<>
<label htmlFor={id} className="customRadio">
<input id={id} name={name} value={id} type="radio" checked={isChecked} onChange={onChange}/>
<span className="label">{label}</span>
<span className="checkmark"></span>
</label>
</>
);
};
export default CustomRadioButton;
import CustomRadioButton from '../CustomRadioButton/CustomRadioButton';
const SortBy = () => {
const [sortValue, setSortValue] = useState<String>('none')
const sortByData = [
{
id: 'highest',
name: 'sortBy',
label: 'Highest to Lowest Time Per Question',
},
{
id: 'lowest',
name: 'sortBy',
label: 'Lowest to Highest Time Per Question',
},
{ id: 'questionType',
name: 'sortBy',
label: 'Question Type' },
{
id: 'remark',
name: 'sortBy',
label: 'Correct | Incorrect | Unanswered',
},
{
id: 'none',
name: 'sortBy',
label: 'None',
},
];
const handleOnchange = (e:React.ChangeEvent<HTMLInputElement> ) => {
setSortValue(e.currentTarget.value)
console.log(sortValue,"...")
};
let checked: any = '';
return (
<>
<div className="SortBy">
<h3 className="filtersTitle">SORT BY:</h3>
{sortByData?.map((d: any, i: any) => {
return (
<div className="Radiochildren" key={i}>
<CustomRadioButton
label={d?.label}
id={d?.id}
name={d?.name}
onChange={handleOnchange}
isChecked={sortValue === d?.id}
/>
</div>
);
})}
</div>
</>
);
};
export default SortBy;
我试过设置 preventdefault 还是没用
你的代码工作正常。
handleOnchange
内的控制台日志显示旧状态,因为它在组件重新渲染之前触发。如果将该控制台日志移到 handleOnchange
函数之外,您将看到该组件正在使用正确的值重新呈现。
这是沙箱中的代码,带有附加控制台日志:https://codesandbox.io/s/react-typescript-forked-vgigdd?file=/src/App.tsx
如果您需要在
handleOnchange
函数中访问该值,则只需使用 e.target.value
.