首页 > 解决方案 > 在父级别维护 onClick 属性,而不是将其传递给子组件

问题描述

经过半小时的谷歌搜索后,我一无所获。我在我的项目中使用打字稿,并且在这种情况下,我有一个带有孩子的父组件。我想onClick为该子级设置一个属性,但我希望该属性在父级解析,而不是作为道具传递并在子级解析。

const PasswordField: React.FC<{ name: string; placeholder: string }> = ({ name, placeholder }) => {

    const passwordRef = useRef<HTMLInputElement>(null);

    const foo = () => {
        //do something
    }

    return (
        <FormField name={name} >
            <InputField ref={passwordRef} name={name} placeholder={placeholder} type="password" />
            <LockIcon width={"20px"} height={"20px"} stroke={theme.colors.supportGrey10} />
            // i want foo to run here at parent level, instead of running inside the child component
            <EyeIcon width={"20px"} height={"20px"} stroke={theme.colors.supportGrey10} onClick={foo} />
        </FormField>
    )
};

export default PasswordField

EyeIcon组件行上,我收到以下错误:

Property 'onClick' does not exist on type 'IntrinsicAttributes & ISVGProps & { children?: ReactNode; }'.ts(2322)

哪个是对的。我对孩子没有onClick财产,我也不想。

有没有办法不出现这个错误?对打字稿说该onClick属性应该在父级解决而不是传递给子级?

标签: javascriptreactjstypescript

解决方案


推荐阅读