【问题标题】:What is react component in typescript inteface?什么是打字稿界面中的反应组件?
【发布时间】:2021-09-12 10:05:37
【问题描述】:

在打字稿界面中,我们可以定义,如:

export interface ViewContainerProps {
  style?: ViewStyle | ViewStyle[];
  children?: React.ReactNode
  aString:string
  aNumber:number
}

我想写一个自定义的顶级<View>,覆盖所有屏幕,它看起来像这样:

const VIEW_CONTAINER: ViewStyle = {
  width: windowWidth,
  height: windowHeight,
};
export interface ViewContainerProps {
  style?: ViewStyle | ViewStyle[];
  children?: React.ReactNode ///no , something wrong
}
export const ViewContainer = (props: ViewContainerProps) => {
  const {style, children} = props;
  return <View style={[style, VIEW_CONTAINER]}>{children}</View>;
};

我想让孩子们返回React component 进行交互并执行 React 组件所做的任何事情,我可以在 typescript 界面中放入什么类型的 React?我读了一些文档,说 React.reactNode a light, stateless, immutable, virtual representation of a DOM node,感觉这不是我在创建包装所有子组件的顶级组件时想要的

请帮忙,非常感谢

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    React.ReactNode 是正确的类型。确定这一点的一种方法是查看功能组件 React.FC 的内置类型,您可以看到它将 children 属性键入为 React.ReactNode

    您应该为组件使用 React.FC,而不是自己添加 children 属性:

    import React from "react"
    
    export interface ViewContainerProps {
      style?: ViewStyle | ViewStyle[];
    }
    
    export const ViewContainer: React.FC<ViewContainerProps> = (props) => {
      const { style, children } = props;
      return <View style={[style, VIEW_CONTAINER]}>{children}</View>;
    };
    

    【讨论】:

    • 所以我可以使用 React.ReactNode?好吧,我使用 React.ReactNode,因为它将包含我所有的应用程序操作和事物,例如同步到服务器或重新渲染,简而言之,反应事物,所以当我可以使用 React.ReactNode 时听起来很棒,谢谢你的回答,顺便说一句
    【解决方案2】:

    你可以使用 React.FunctionComponent 或 React.FC

    import React, { FC } from 'react';
    
    export const ViewContainer: FC = (props: ViewContainerProps) => {
      const {style, children} = props;
      return <View style={[style, VIEW_CONTAINER]}>{children}</View>;
    };
    

    【讨论】:

    • 非常感谢您的回答,我将使用 React.FC
    猜你喜欢
    • 2017-11-28
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 2016-08-13
    • 2014-02-12
    • 2020-08-21
    • 2022-08-13
    • 1970-01-01
    相关资源
    最近更新 更多