I'm using a Map
to store the state of my component. Within this component, I have 3 groups, and in each group I have radio buttons. I have this array so that I can set values by default:
我正在使用Map来存储我的组件的状态。在这个组件中,我有3个组,每个组中都有单选按钮。我有这个数组,因此可以在默认情况下设置值:
const defaultOptions = [
{ label: "Mark", value: "mark" },
{ label: "Steve", value: "steve" },
{ label: "Paul", value: "Paul" }
];
How can I set values by default using this array?
如何使用此数组设置缺省值?
Here's live DEMO
这是现场演示
更多回答
优秀答案推荐
You can create the Map
based on the array of defaults like so:
您可以基于默认数组创建贴图,如下所示:
// in the App component
useEffect(() => {
const newPosts = someJson;
setPosts(newPosts);
setSearchResults(newPosts);
setCheckboxStates(
new Map(defaultOptions.map(o =>
[newPosts.find(p => p.fields.some(f => f.name === o.label)).label, [o]]))
);
}, []);
you must use the checked
prop
你必须使用检测道具
<article>
{showGroup && (
<div>
{post.fields?.map((field: any, idx: number) => {
const itemsSelected = checkboxStates
.get(post.label)
?.some((o) => o.label === field.name)
const isChecked =
itemsSelected !== null || itemsSelected !== undefined ? itemsSelected : defaultOptions.some(item => item.value === field.value);
return (
<div key={idx}>
<input
type="radio"
name={post.label}
value={field.value}
checked={isChecked}
onChange={(e) =>
handleRadiobuttonChange(field, e.target.checked)
}
/>
<span>{field?.name}</span>
<br />
</div>
);
})}
</div>
)}
</article>
更多回答
@Devmix No problem.
@DevMix没有问题。
It doesn't work. Can you provide a working live demo, please?
它不起作用。你能提供一个现场工作演示吗?
我是一名优秀的程序员,十分优秀!