![](/img/trans.png)
[英]How to fix eslint warning warning JSX attribute values should not contain functions created in the same scope react-perf/jsx-no-new-function-as-prop
[英]How to fix the error jsx no new function as prop with typescript and react?
我想使用 typescript 修復 eslinting 規則錯誤 jsx no new function as prop 並做出反應。
我有如下代碼,
const Parent = () => {
const handleChange = useCallback((value: boolean) => {
setField(value);
}, [setField]);
return (
<RadioButton label="first" onChange={() => handleChange(true)}/> //error here
<RadioButton label="second" onChange={() => handleChange(false)}/> //error here
);
}
我知道使用 onChange={() => handleChange(true)} 是一種反模式,因此是錯誤的。 但我試過了
onChange={handleChange(true)} this causes maximum state update depth reached error.
我該如何解決這個問題,以至於我看不到 jsx no new function 作為道具錯誤。 有人可以幫我解決這個問題。 謝謝。
只需將回調作為道具傳遞:
<RadioButton label="first" onChange={handleChange}/>
不能 100% 確定您的用例,但我建議不要使用useCallback
:
const handleChange = (value: boolean) => {
setField(value);
};
還要確保RadioButton
的onChange
道具具有簽名(value: boolean) => void
並且不使用某種React.ChangeEvent
。 如果它使用React.ChangeEvent
,您將不得不調整handleChange
的簽名。
嘗試這個
const Parent = () => ( <> <WrapRadioButton label='first' bool /> <WrapRadioButton label='second' bool={false} /> </> ) const WrapRadioButton = (props) => { const [field,setField] = React.useState(false) const handleChange = () => { setField(props.bool); }; return ( <RadioButton onChange={handleChange} {...props} /> ); }; const RadioButton =(props)=>{ const myProps = props return (<div>lalal</div>) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.