[英]What is the point of having "value" property in React <input>?
I have already known that the "value" is used with Controlled components.我已经知道“值”与受控组件一起使用。 But at this test , when I delete the property
value = {controlledValue}
it still works perfectly fine.但是在这个测试中,当我删除属性
value = {controlledValue}
它仍然可以正常工作。
import React, { useState } from "react";
export const Controlled = props => {
const [controlledValue, updateControlledValue] = useState("");
const handleChange = event => {
updateControlledValue(event.target.value);
};
const handleSubmit = event => {
event.preventDefault();
props.handleSubmittedData({
controlled: controlledValue
});
};
return (
<form onSubmit={handleSubmit}>
<h2>Controlled</h2>
<input
name="controlled"
placeholder="controlled"
type="text"
value={controlledValue}
onChange={handleChange}
/>
<button disabled={!controlledValue} type="submit">
Submit
</button>
</form>
);
};
What is the point of having the value
property when we have already handled the controlledValue
state with handleChange
?当我们已经用
handleChange
处理了controlledValue
state 时,拥有value
属性有什么意义呢?
It is not necessary to add value = {controlledValue}没有必要添加 value = {controlledValue}
But it could be helpful when you need to give a specific value to the input box before start typing or after some API call, or action.但是当您需要在开始键入之前或在某些 API 呼叫或操作之后为输入框提供特定值时,它可能会有所帮助。 (This is what mean by the term "controlled" you can control the value after some action)
(这就是术语“受控”的意思,您可以在执行某些操作后控制该值)
For example例如
If you have a product edit page and you need to edit the name of a product that is already stored in DB.如果您有一个产品编辑页面,并且需要编辑已存储在数据库中的产品名称。 in this case you need to display the initial value which is stored in DB and the user is able to edit and save that.
在这种情况下,您需要显示存储在数据库中的初始值,并且用户可以编辑和保存它。
for such a case after we get a successful response from API just assign the product name to value.对于这种情况,在我们从 API 获得成功响应后,只需将产品名称分配给值即可。
or或者
If you need to add a specific text to an input box when you click a button You can just assign the specific text to value.如果您需要在单击按钮时将特定文本添加到输入框 您可以将特定文本分配给值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.