【问题标题】:Passing useState as props, hook isn't recognized as function将 useState 作为道具传递,钩子不被识别为函数
【发布时间】:2023-01-19 05:32:19
【问题描述】:

我正在尝试将“section”和“setSection”从父母传递给孩子。

我正在关注这个,但它对我不起作用: Passing useState as props in typescript

错误: 未处理的运行时错误 类型错误:setSection 不是一个函数

父组件:

export default function CareerProgression() {
   const [section, setSection] = useState< 'video' | 'condensed' | 'full' >('condensed');

   return (
      <ModuleToggle_withState section={section} setSection={setSection} />
   );
}

孩子:

import { Dispatch, useEffect, SetStateAction } from 'react';

export function ModuleToggle_withState(section:any, setSection:Dispatch<SetStateAction<any>>) {
// Currently I'm using "any" just so I can test passing useState props

   return (
      <>
         <SegmentedControl
            defaultValue='video'
            value={section}
            onChange={(value: 'video' | 'condensed' | 'full') => setSection(value)}
         />
      </> 
   ); 
}

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    组件只有一个参数,它是一个对象

    ModuleToggle_withState({
      section,
      setSection
    }: {
      section:any,
      setSection:Dispatch<SetStateAction<any>>
    })
    

    【讨论】:

      猜你喜欢
      • 2022-08-12
      • 2020-05-03
      • 2019-07-03
      • 2019-11-05
      • 2019-09-25
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 2022-11-05
      相关资源
      最近更新 更多