如何传递带参数的函数与打字稿

时间:2021-04-04 09:43:36

标签: javascript reactjs typescript next.js

我想将一个 handleClick 传递给儿子,这样我就不必做两次了。代码如下:

妈妈:

const Mother = () => {
    const [selectedOption, setSelectedOption] = useState<'rooms' | 'questions' | 'notifications'>('rooms')

    const customSectionStyle = 'bg-primary-500 text-white hover:bg-primary-600'

    //handle click
    const handleClick = (href, section) => {
      setSelectedOption(section);
      router.push(href)
    }
    return(
        <>
            <Son onClick={() => handleClick} selectedOption={selectedOption} customSectionStyle={customSectionStyle}/>
        </>
    )
}

儿子:

const Son: React.FC<{ selectedOption?: string | '', onClick?: (href: string, section: string) => void | void, customSectionStyle?: string | '' }> = (selectedOption, onClick, customSectionStyle) => {
    return(
        <>
            <MyComponent onClick={() => {onClick('/','home')}} customStyle={selectedOption === 'rooms' ? customSectionStyle : ''}/>
            <MyComponent onClick={() => {onClick('/','settings')}} customStyle={selectedOption === 'settings' ? customSectionStyle : ''}/>
        //...
        </>
    )
}

基本上这会设置背景颜色,以防选择或未选择选项。 MyComponent 是一个组件,它接受该道具(和/或其他)并设置自己的内容。

这会引发类型错误_onClick is not a function。 我相信我没有做好。在你看来,我错过了什么?

3 个答案:

答案 0 :(得分:1)

const Son: React.FC<{ selectedOption?: string | '', onClick?: (href: string, section: string) => void | void, customSectionStyle?: string | '' }> = (selectedOption, onClick, customSectionStyle)

替换为

const Son: React.FC<{ selectedOption?: string, onClick?: (href: string, section: string) => void, customSectionStyle?: string }> = ({ selectedOption, onClick, customSectionStyle })

答案 1 :(得分:1)

Son 将使用您必须销毁它或直接从 props 读取的所有 props 调用

(selectedOption, onClick, customSectionStyle) 应该是 ({selectedOption, onClick, customSectionStyle})

const Son: React.FC<{ selectedOption?: string | '', onClick?: (href: string, section: string) => void | void, customSectionStyle?: string | '' }> = ({selectedOption, onClick, customSectionStyle}) => {
    return(
        <MyComponent onClick={() => {onClick('/','home')}} customStyle={selectedOption === 'rooms' ? customSectionStyle : ''}/>
        <MyComponent onClick={() => {onClick('/','settings')}} customStyle={selectedOption === 'settings' ? customSectionStyle : ''}/>
        //...
    )
}

答案 2 :(得分:1)

你确定要返回两个相邻的 MyComponent 吗? 而且我认为您在获取子组件定义中的道具时错过了花括号 =

<块引用>

({ selectedOption, onClick, customSectionStyle })