admin管理员组文章数量:1415476
I got two inputs. If I want to bind the input value with a state variable, I use this -
The state :
const [message, setMessage] = useState('')
const [newUser, setNewUser] = useState('')
The methods the bind them :
const handleMessageChange = (e) => setMessage(e.target.value)
const handleUserChange = (e) => setNewUser(e.target.value)
And I call these methods with the onChange property on the input.
My qusetion :
Can I use a generic handleChange method instead of explicitly creating a method to each input/state pair? If so, how?
I got two inputs. If I want to bind the input value with a state variable, I use this -
The state :
const [message, setMessage] = useState('')
const [newUser, setNewUser] = useState('')
The methods the bind them :
const handleMessageChange = (e) => setMessage(e.target.value)
const handleUserChange = (e) => setNewUser(e.target.value)
And I call these methods with the onChange property on the input.
My qusetion :
Can I use a generic handleChange method instead of explicitly creating a method to each input/state pair? If so, how?
Share Improve this question asked Apr 22, 2020 at 19:49 apollo24apollo24 3136 silver badges20 bronze badges 1- 1 Does this answer your question? stackoverflow./a/56951398/3662110 – jmargolisvt Commented Apr 22, 2020 at 19:57
2 Answers
Reset to default 5You might consider store both user
and message
in one {data}
state holder, and at handleChange
modified just the relevant key in state object
const [data, setData] = useState({user: "", message: ""})
const handleChange = useCallback((e) => setData((prev) => ({ ...prev, [e.target.name]: e.target.value })), []);
<input name="message" value={data.message} onChange={handleChange} />
<input name="user" value={data.user} onChange={handleChange} />
Here's 2 ways to do so: https://codesandbox.io/s/relaxed-pine-zgwfy
Illustrating one of the ways here.
The hooks and handler:
const [message, setMessage] = useState("");
const [newUser, setNewUser] = useState("");
const handleChange = e =>
e.target.name === "message"
? setMessage(e.target.value)
: e.target.name === "user"
? setNewUser(e.target.value)
: "";
The inputs:
<input name="message" value={message} onChange={handleChange} />
<input name="user" value={newUser} onChange={handleChange} />
Hope that helps,
Cheers!
本文标签: javascriptTwo way binding more than one input in React w HooksStack Overflow
版权声明:本文标题:javascript - Two way binding more than one input in React w Hooks - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745174080a2646150.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论