[英]How do I set a value for a <select> with React without using onChange?
I got the following HTML select element我得到以下 HTML 选择元素
<select id="bars" onChange={(e) => onBarChange(e)}>
{props.results.map((bar, y) => (
<option value={bar.id} key={bar.id} data-key={bar.id}>
{bar.name} in {bar.city}
</option>
))}
</select>;
with the following onChange method as a callback:使用以下 onChange 方法作为回调:
const onBarChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setBarId(parseInt(e.target.value));
};
However, whenever theres only one bar in props.results
(props.results.length === 1) then onBarChange(e)
will never be called and thus barId
will always remain 0 (default select value I guess).但是,只要
props.results
(props.results.length === 1) 中只有一个栏,那么onBarChange(e)
将永远不会被调用,因此barId
将始终保持为 0(我猜是默认选择值)。
I tried to put that logic into the submit form like following:我试图将该逻辑放入提交表单中,如下所示:
if(props.results.length === 1) {
setBarId(props.results[0].id)
}
but that isn't working either.但这也不起作用。 If I console log
props.results[0].id
I get the correct id but if I console log barId
right after this its still 0 again.如果我控制台 log
props.results[0].id
我得到正确的 id 但如果我控制台 log barId
在这之后它仍然是 0。 How can that happen?怎么会这样? Is a rerender triggered and the select immediately sets the default 0 as the state again?
是否触发了重新渲染并且选择立即再次将默认值 0 设置为状态?
How can I resolve this so the submit button wrapping this select is sending the correct barId to the backend whenver theres just one bar in props.results
(should of course also work with multiple bars..)?我该如何解决这个问题,以便包装此选择的提交按钮在
props.results
只有一个栏时将正确的 barId 发送到后端(当然也应该与多个栏一起使用..)?
When you are creating barId using useState pass default value.当您使用 useState 传递默认值创建 barId 时。
const [barId, setBarId] = useState(props?.results[0]?.id ?? 0)
const onBarChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setBarId(parseInt(e.target.value));
};
<select id="bars" onChange={(e) => onBarChange(e)}>
{props.results.map((bar, y) => (
<option value={bar.id} key={bar.id} data-key={bar.id}>
{bar.name} in {bar.city}
</option>
))}
</select>;
Another thing you can do is add an empty value first.您可以做的另一件事是先添加一个空值。
<select id="bars" onChange={(e) => onBarChange(e)}>
<option>Select Bar</option>
{props.results.map((bar, y) => (
<option value={bar.id} key={bar.id} data-key={bar.id}>
{bar.name} in {bar.city}
</option>
))}
</select>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.