簡體   English   中英

如何傳遞帶有參數的 function 與 typescript 反應

[英]How to pass a function with parameters in react with typescript

我想將 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 我相信我沒有正確地做到這一點。在你看來,我錯過了什么?

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 })

兒子將被調用所有你必須破壞它的道具或直接從道具中讀取

(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: ''}/> //... ) }

你確定要在那里返回兩個相鄰的 MyComponent 嗎? 而且我認為您在獲取子組件定義中的道具時會錯過花括號=

({ selectedOption, onClick, customSectionStyle })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM