繁体   English   中英

如何修复错误 jsx no new function as prop with typescript 并做出反应?

[英]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);
};

还要确保RadioButtononChange道具具有签名(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM