【发布时间】:2021-04-04 09:43:36
【问题描述】:
我想将 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 不是函数。 我认为我做得不对。在您看来,我错过了什么?
【问题讨论】:
标签: javascript reactjs typescript next.js