React報錯之You provided a `checked` prop to a form field
- 2022 年 8 月 25 日
- 筆記
正文從這開始~
總覽
當我們在多選框上設置了checked 屬性,卻沒有onChange 處理函數時,會產生"You provided a checked prop to a form field without an onChange handler"錯誤。為了解決該錯誤,可以使用defaultChecked 屬性,或者在表單欄位上設置onChange 屬性。
這裡有個例子用來展示錯誤是如何發生的。
// App.js
export default function App() {
// ⛔️ Warning: You provided a `checked` prop to a form field
// without an `onChange` handler. This will render a read-only field.
// If the field should be mutable use `defaultChecked`.
// Otherwise, set either `onChange` or `readOnly`.
return (
<div>
<input type="checkbox" id="subscribe" name="subscribe" checked={true} />
</div>
);
}
上述程式碼片段的問題在於,我們在input表單上設置了checked屬性,但卻沒有提供onChange事件處理器。這使得input的checked屬性成為靜態的。
defaultChecked
解決該錯誤的一種方式是,使用defaultChecked屬性取而代之。
export default function App() {
return (
<div>
<input
type="checkbox"
id="subscribe"
name="subscribe"
defaultChecked={true}
/>
</div>
);
}
defaultChecked屬性為多選框設置了一個初始值,但是該值不是靜態的,是可以被更改的。
defaultChecked屬性常被用於不受控(不被開發者控制)的多選框。這意味你必須使用ref或者表單元素來訪問表單欄位的值。
// App.js
import {useRef} from 'react';
// 👇️ Example of uncontrolled checkbox
export default function App() {
const ref = useRef(null);
const handleClick = () => {
console.log(ref.current.checked);
};
return (
<div>
<input
ref={ref}
type="checkbox"
id="subscribe"
name="subscribe"
defaultChecked={true}
/>
<button onClick={handleClick}>Click</button>
</div>
);
}
每當你點擊按鈕時,多選框的checked值就會被列印到控制台上。
onChange
或者,我們可以在input表單欄位上設置onChange屬性,並處理事件。
import {useState} from 'react';
export default function App() {
const [isSubscribed, setIsSubscribed] = useState(false);
const handleChange = event => {
setIsSubscribed(event.target.checked);
// 👇️ this is the checkbox itself
console.log(event.target);
// 👇️ this is the checked value of the field
console.log(event.target.checked);
};
return (
<div>
<input
type="checkbox"
id="subscribe"
name="subscribe"
onChange={handleChange}
checked={isSubscribed}
/>
</div>
);
}
我們做的第一件事是將input的checked值存儲在一個叫做isSubscribed的狀態變數中。
我們在多選框上設置了
onChange屬性,所以每當值改變時,handleChange函數就會被調用。
我們可以通過event對象上的target屬性來訪問多選框。類似地,我們可以通過event.target.checked來訪問多選框的值。
初始值
如果你想為多選框提供一個初始值,只需將它傳遞給useState()鉤子。
import {useState} from 'react';
export default function App() {
// 👇️ set checked to true initially
const [isSubscribed, setIsSubscribed] = useState(true);
const handleChange = event => {
setIsSubscribed(event.target.checked);
// 👇️ this is the checkbox itself
console.log(event.target);
// 👇️ this is the checked value of the field
console.log(event.target.checked);
};
return (
<div>
<input
type="checkbox"
id="subscribe"
name="subscribe"
onChange={handleChange}
checked={isSubscribed}
/>
</div>
);
}
我們向useState鉤子傳遞了true,所以複選框的初始值將是checked。
