[英]How to move uncontrolled component to controlled component
I am creating a form by custom form react bootstrap, but I have an issue that,我正在通过自定义表单 react bootstrap 创建表单,但我有一个问题,
A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component
That is my input form is uncontrolled.那是我的输入表单不受控制。 How can I change it to controlled input form to allow user to enter what they want?
如何将其更改为受控输入表单以允许用户输入他们想要的内容?
const ProductForm = ({ product, onSave }) => {
const [value, setValues] = useState(product);
useEffect(() => {
setValues({
product: {
image: "",
name: "",
price: 0,
description: "",
categoty: ""
}
});
}, []);
const handleInputChange = event => {
// Create new product to update
const newPropdudct = {
...value,
[event.target.name]: event.target.value
}
// Update new product for value
setValues(newPropdudct);
}
/////////////////////////////////////////////////////////// ///////////////////////////////////////////////// /////////
<Form.Group>
<Form.Group>
<Form.File
id="image"
label="Image choose"
value={value.image}
onChange={handleFileChange} />
</Form.Group>
</Form.Group>
<Form.Group controlId="name">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter product name"
value={value.name}
name="name"
onChange={handleInputChange}
/>
</Form.Group>
The reason is, in state you defined:原因是,在您定义的状态下:
const [value, setValues] = useState(product);
also in your useEffect there is a product property and inside that a name property:在你的 useEffect 中还有一个 product 属性,里面有一个 name 属性:
setValues({
product: {
image: "",
name: "",
price: 0,
description: "",
categoty: ""
}
});
and in your form control并在您的表单控件中
value={value.name}
during the first rendering the value of the form will be undefined, and the input field will get its value as:在第一次渲染期间,表单的值将是未定义的,并且输入字段将获得其值:
value={undefined}
Because of that, the input field will become uncontrolled.因此,输入字段将变得不受控制。
it should be :它应该是 :
value={value.product.name}
and your handleInputChange function should be:并且您的 handleInputChange 函数应该是:
handleInputChange = event => {
// Create new product to update
const newPropdudct = {
product: {
...value.product,
[event.target.name]: event.target.value
}
}
// Update new product for value
setValues(newPropdudct);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.