繁体   English   中英

如何使用 react、typescript 和 styled-component 将 onclick 方法从父组件传递给子组件?

[英]How to pass onclick method to child component from parent using react, typescript, and styled-component?

我想使用 react 和 typescript 将 onclick 方法从孩子传递给父母。

我想做什么?

我有一个渲染子组件的父组件,如下所示,

function Parent() {
    const [isDialogOpen, setisDialogOpen] = useState('');
    const set =() => {
        setisDialogOpen(!isDialogOpen);
    }

    return (
        <Child size={16} fontSize={12}/>
    );
}

interface Props {
    size?: number;
    fontSize?: number;
}

const Child = styled.div<Props>`
    font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
    size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;

 export default Child;

现在,如何将 onClick 方法添加到子组件中,以便设置 isDialogOpen state?

我试过什么?

我试图做类似下面的事情,

function Parent() {
    const [isDialogOpen, setisDialogOpen] = useState('');
    const setDialog =() => {
        setisDialogOpen(!isDialogOpen);
    }

    return (
        <Child onClick={setDialog} size={16} fontSize={12}/>
    );
}

interface Props {
    onClick?: () => void;
    size?: number;
    fontSize?: number;
}

const Child = styled.div<Props>`
    font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
    size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;

 export default Child;

但是如何将 onClick 方法添加到这条线附近的 div 中?

const Child = styled.div<Props>`
    font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
    size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;







    

您应该用组件包装Child并为其包装器提供onClick事件侦听器

检查这个答案

只需用 function 包装子组件。

const StyledChild = styled.div<Props>`
    font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
    size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;

const Child = ({fontSize, size, onClick}: Props) => {
  return (
     <StyledChild onClick={onClick} fontSize={fontSize} size={size} />
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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