gpt4 book ai didi

How to set values by default using Radio buttons?(如何使用单选按钮设置默认值?)

翻译 作者:bug小助手 更新时间:2023-10-26 21:46:08 24 4
gpt4 key购买 nike



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 checkedprop

你必须使用检测道具


    <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>


更多回答

Demo

演示

@Devmix No problem.

@DevMix没有问题。

It doesn't work. Can you provide a working live demo, please?

它不起作用。你能提供一个现场工作演示吗?

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