簡體   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