简体   繁体   中英

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

I want to pass the onclick method from child to parent using react and typescript.

what I am trying do?

I have a parent component which renders child component and is like below,

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;

Now, how can I add onClick method to the Child component such that it sets the isDialogOpen state?

what I tried?

I was trying to do something like below,

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;

But how can I add the onClick method to div near this line?

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







    

You should wrap the Child with a component and give it's wrapper an onClick event listener

check this answer

Just wrap Child component with a 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} />
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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