[英]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.