简体   繁体   中英

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.

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. (Imagine there's another button that can change 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

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. The parent is very possible to save the user input in its state and could replace it's value if the "button" is clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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