【问题标题】:Send onClick function as props to a component in React with Typescript使用 Typescript 将 onClick 函数作为道具发送到 React 中的组件
【发布时间】:2022-01-12 16:49:57
【问题描述】:

我是 Typescript 的新手,我必须编写一个父组件,将 onClick 作为 props 发送到子组件,其中的按钮在单击时触发 onClick 的功能。

代码如下:

export function ParentComponent(props: ParentComponentProps) { 
  const [isOpened, toggleModal] = useToggle(false);
 // useToggle is a custom hook that toggles a boolean
  ...
  const onClick = () => {
    toggleModal();
  }

  return (
          <ChildComponent onClick={onClick} />
         );
}

子组件不知道怎么定义接口,这里应该放什么?

export interface ChildComponentProps {
   onClick: <unknown>();  // what to add here?
}

这是子组件:

export function ChildComponent({onClick}: ChildComponentProps) {
   ...
   return ( 
            <div>
            ...
               <ButtonComponent 
                  onClick={() => onClick()}
                  ...
               />
            ...
           );
}

有什么想法可以添加到界面中,或者是否应该有任何其他更改才能使 Typescript 正确?

【问题讨论】:

    标签: javascript reactjs typescript react-hooks


    【解决方案1】:

    对于像 onClick 这样的函数,你必须描述输入参数和输出,或者只写函数(尽管为了更好的类型检查你不应该只写函数)。

    所以是这样的:

    onClick: () => void
    

    如果你的函数得到一个数字并返回一个字符串,你应该这样写:

    onClick: (n: number) => string
    

    【讨论】:

      【解决方案2】:

      父组件:

      interface OnClickIdInterface {
          (): void,
      }
      
      export interface parentPropsInterface {
          onClick?: OnGetIdInterface;
      }
       
      render() {
          return <ChildComponent onClick={(id) => this.onClick(id)}/>
       }
      

      子组件:

      const HomePresentation: React.FunctionComponent<parentPropsInterface> = ({onClick}) => {
          return (
              <div onClick={()=>onClick()}>
                 some content
              </div>
          )
      }
      

      【讨论】:

        【解决方案3】:

        以下代码应该可以工作。但这取决于ButtonComponent。使用React.MouseEventHandler&lt;T = Element&gt; 作为类型。

        export interface ChildComponentProps {
           onClick: React.MouseEventHandler<ButtonComponent>
        }
        
        export function ChildComponent({onClick}: ChildComponentProps) {
           ...
           return ( 
                    <div>
                    ...
                       <ButtonComponent 
                          onClick={() => onClick()}
                          ...
                       />
                    ...
                   );
        }
        

        如果不正确请通知我。

        【讨论】:

          猜你喜欢
          • 2023-03-12
          • 2022-01-23
          • 2020-03-12
          • 2021-04-21
          • 2021-07-29
          • 2019-12-31
          • 2021-06-23
          • 2018-08-22
          • 2020-08-09
          相关资源
          最近更新 更多