react bootstrap form.switch未按预期工作

huangapple go评论72阅读模式
英文:

react bootstrap form.switch not working as expected

问题

以下是翻译好的部分:

我已经使用了 react-bootstrap Form我需要使用开关按钮如果条件为真则必须显示输入框否则输入框将不会显示

const initialState = {
  billingType: "",
  basicFees: false,
  basicFeesCharges: 0
}
const [form, setForm] = useState(initialState);
const [toggle, setToggle] = useState(false);

useEffect(() => {
  console.log('toggle effect', toggle);
  console.log('use effect form', form);
}, [toggle, form]);

const setField = (field, value) => {
  console.log("field", field);
  console.log("value", value);
  setForm({
    ...form,
    [field]: value,
  });
  console.log("set field", form);
  // 检查是否存在错误,并从错误对象中移除它们:
  if (!!errors[field]) {
    setErrors({
      ...errors,
      [field]: null,
    });
  }
};

**JSX**

<Form.Group>
  <Form.Check
    type="switch"
    name="basicFees"
    id="custom-switch"
    label="Basic Fees"
    checked={toggle}
    onChange={(e) => {
      setToggle(!toggle);
      setField("basicFees", toggle);
    }}
  />
  这里的费用 {form && form.basicFees ? "开" : "关";}
  {form && form.basicFees ? (
    <>
      <Form.Label>基本费用</Form.Label>
      <Form.Control
        type="text"
        name="basicFeesCharges"
        onChange={(e) =>
          setField("basicFeesCharges", e.target.value)
        }
        isInvalid={!!errors.basicFeesCharges}
      />
      <Form.Control.Feedback type="invalid">
        {errors.basicFeesCharges}
      </Form.Control.Feedback>
    </>
  ) : (
    ""
  )}
</Form.Group>

问题使用上面的代码我没有得到正确的结果默认情况下开关是关闭的当我第一次单击时理论上应该显示 `basicFeesCharges` 的输入框但它不显示此时开关是 '打开'第二次单击时它显示 `basicFeesCharges` 的输入框并且开关按钮此时为 '关闭'
这意味着无论如何在 onChange 事件中使用了 useEffect状态或表单都没有正确更新因此开关按钮的行为与预期相反

作为初学者尝试不同的语法或代码后我仍然无法找到错误或正确的解决方案请帮助和指导谢谢
英文:

I have used react-bootstrap Form. I need to use switch button. If that is true then have to show input box else input box will not show.

  const initialState = {
billingType: &quot;&quot;,
basicFees: false,
basicFeesCharges: 0
}
const [form, setForm] = useState(initialState);
const [toggle, setToggle] = useState(false);
useEffect(() =&gt; {
console.log(&#39;toggle effect&#39;,toggle);
console.log(&#39;use effect form&#39;,form);
}, [toggle,form]);
const setField = (field, value) =&gt; {
console.log(&quot;field&quot;, field);
console.log(&quot;value&quot;, value);
setForm({
...form,
[field]: value,
});
console.log(&quot;set field &quot;, form);
// Check and see if errors exist, and remove them from the error object:
if (!!errors[field]) {
setErrors({
...errors,
[field]: null,
});
}
};

JSX

 &lt;Form.Group&gt;
&lt;Form.Check
type=&quot;switch&quot;
name=&quot;basicFees&quot;
id=&quot;custom-switch&quot;
label=&quot;Basic Fees&quot;
checked={toggle}
onChange={(e) =&gt; {
setToggle(!toggle);
setField(&quot;basicFees&quot;,toggle);
}}
/&gt;
Here fees {form &amp;&amp; form.basicFees ? &quot;on&quot; : &quot;off&quot;}
{form &amp;&amp; form.basicFees ? (
&lt;&gt;
&lt;Form.Label&gt;Basic Fees Charges&lt;/Form.Label&gt;
&lt;Form.Control
type=&quot;text&quot;
name=&quot;basicFeesCharges&quot;
onChange={(e) =&gt;
setField(&quot;basicFeesCharges&quot;, e.target.value)
}
isInvalid={!!errors.basicFeesCharges}
/&gt;
&lt;Form.Control.Feedback type=&quot;invalid&quot;&gt;
{errors.basicFeesCharges}
&lt;/Form.Control.Feedback&gt;
&lt;/&gt;
) : (
&quot;&quot;
)}
&lt;/Form.Group&gt;

Problem: with above code, I am not getting proper result. By default, switch is off. When I first click then ideally it should show input box of basicFeesCharges but it does not shows and switch is 'On' at that time. On second click it shows input box of basicFeesCharges and switch button is 'Off' that time.
Means state or form does not updating properly onChange even if used useEffect. So giving opposite result for switch button.

As a beginner, I am not able to find bug or correct solution even after trying different syntax or code. Please help and guide. Thanks.

答案1

得分: 0

因为你的onChange函数的原因

onChange={(e) => {
    setToggle(!toggle);
    setField("basicFees", toggle);
}}

setToggle是异步的,所以在setField中的toggle在第一次仍然是false。所以尝试这个

onChange={(e) => {
    const newToggle = !toggle;
    setToggle(newToggle);
    setField("basicFees", newToggle);
}}
英文:

Its because of your onChange function

onChange={(e) =&gt; {
setToggle(!toggle);
setField(&quot;basicFees&quot;,toggle);
}}

setToggle is asynchronous, so the toggle in setField is still false at 1st time. So try this

onChange={(e) =&gt; {
const newToggle = !toggle;
setToggle(newToggle);
setField(&quot;basicFees&quot;, newToggle);
}}

huangapple
  • 本文由 发表于 2023年2月24日 15:46:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定