简体   繁体   English

让表单控件的值既来自props也来自用户输入

[英]Letting a form-control's value be both from props and from user input

I have set it up like this: 我已经这样设置了:

<input className="form-control" id="focusedInput" type="text" value={props.myValue />

This of course will give a warning about missing onChange. 这当然会警告您缺少onChange。

What I really want to do is allow this field to be user-editable (and update props.myValue as soon as it's edited), but at the same time, if props.myValue changes, it will update to props.myValue as well. 我真正想做的是允许该字段可由用户编辑(并在编辑后立即更新props.myValue),但是同时,如果props.myValue更改,它将也更新为props.myValue。 (Imagine there's another button that can change props.myValue.) (想象一下还有另一个按钮可以更改props.myValue。)

How can I do it? 我该怎么做?

This is the famous one, I suggest reading the full article once, but the solution is in this section: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#preferred-solutions 这是著名的文章,我建议阅读全文,但解决方案在此部分中: https : //reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state。 html#preferred-solutions

The idea is to let the parent of this <input> to control the props, so you make onChange up to the parent, then the parent can receive user input and manage that "button" you mention, so the props of this <input> is well decided. 想法是让此<input>的父控件来控制道具,因此您将onChange设置为父项,然后父项可以接收用户输入并管理您提到的“按钮”,因此此<input>props是很好的决定。 The parent is very possible to save the user input in its state and could replace it's value if the "button" is clicked. 父级很有可能将用户输入保存为state ,如果单击“按钮”,则可以替换其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM