跳至內容

react/checked-requires-onchange-or-readonly 吹毛求疵

此規則的作用

此規則強制輸入元素的 checked 屬性必須要有 onChange 或 readonly 屬性。當同時使用 checked 和 defaultChecked 屬性時也會發出警告。

範例

此規則的錯誤程式碼範例

jsx
<input type="checkbox" checked />
<input type="checkbox" checked defaultChecked />
<input type="radio" checked defaultChecked />

React.createElement('input', { checked: false });
React.createElement('input', { type: 'checkbox', checked: true });
React.createElement('input', { type: 'checkbox', checked: true, defaultChecked: true });

此規則的正確程式碼範例

jsx
<input type="checkbox" checked onChange={() => {}} />
<input type="checkbox" checked readOnly />
<input type="checkbox" checked onChange readOnly />
<input type="checkbox" defaultChecked />

React.createElement('input', { type: 'checkbox', checked: true, onChange() {} });
React.createElement('input', { type: 'checkbox', checked: true, readOnly: true });
React.createElement('input', { type: 'checkbox', checked: true, onChange() {}, readOnly: true });
React.createElement('input', { type: 'checkbox', defaultChecked: true });

參考資料

以 MIT 許可證發布。