[英]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.