如何指定和更改useState中的对象。

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

how to specify and change object in object of useState

问题

const [info, setInfo] = useState({
    idx: 1,
    user: {
        name: ""
    }
});

function handle(e) {
    setInfo(prev => ({ ...prev, [e.target.name]: e.target.value }));
}

<input type="text" onChange={(e) => handle(e)} name="idx" /> // works!
<input type="text" onChange={(e) => handle(e)} name="user.name" /> // NOT work

如何更改useState中的user.name值作为文本输入的name属性?

尝试:
name="user.name"
name="user['name']"

英文:
    const [info, setInfo] = useState({
        idx: 1,
        user: {
            name: &quot;&quot;
        }
    });
    function handle(e) {
        setInfo(prev =&gt; ({ ...prev, [e.target.name]: e.target.value }));
    }
     &lt;input type=&quot;text&quot; onChange={(e) =&gt; handle(e)} name=&quot;idx&quot; /&gt; // works!
     &lt;input type=&quot;text&quot; onChange={(e) =&gt; handle(e)} name=&quot;user.name&quot; /&gt; // NOT work

how can i change user.name value of useState as name attribute of text input?

try:
name="user.name"
name="user['name']"

答案1

得分: 1

因为 name 嵌套在 user 中,所以最好有一个独立的 onChange 函数,因为你当前的 handle 函数只会使用 e.target.name 来设置顶层键。

<input type="text" onChange={(e) => setInfo(prevState => ({...prevState, user: {name: e.target.value}})}/>
英文:

Because name is nested in user it would be easier to have an independent onChange function, as your current handle function will only set top-level keys using e.target.name

&lt;input type=&quot;text&quot; onChange={(e) =&gt; setInfo(prevState =&gt; {...prevState, user: {name: e.target.value}})}/&gt;

huangapple
  • 本文由 发表于 2023年2月6日 18:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360180.html
匿名

发表评论

匿名网友

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

确定