[英]How to move uncontrolled component to controlled component
我正在通过自定义表单 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
那是我的输入表单不受控制。 如何将其更改为受控输入表单以允许用户输入他们想要的内容?
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>
原因是,在您定义的状态下:
const [value, setValues] = useState(product);
在你的 useEffect 中还有一个 product 属性,里面有一个 name 属性:
setValues({
product: {
image: "",
name: "",
price: 0,
description: "",
categoty: ""
}
});
并在您的表单控件中
value={value.name}
在第一次渲染期间,表单的值将是未定义的,并且输入字段将获得其值:
value={undefined}
因此,输入字段将变得不受控制。
它应该是 :
value={value.product.name}
并且您的 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.