简体   繁体   English

如何在 TypeScript 中使用带有 React 无状态功能组件的子级

[英]How to use children with React Stateless Functional Component in TypeScript

Using TypeScript with React we no longer have to extend React.Props in order for the compiler to know that all react component props can have children:将 TypeScript 与 React 一起使用,我们不再需要扩展React.Props以使编译器知道所有 React 组件道具都可以有孩子:

interface MyProps { }

class MyComponent extends React.Component<MyProps, {}> {
  public render(): JSX.Element {
    return <div>{this.props.children}</div>;
  }
}

However, it doesn't seem to be the case for stateless functional components:但是,无状态功能组件似乎并非如此:

const MyStatelessComponent = (props: MyProps) => {
  return (
    <div>{props.children}</div>
  );
};

Emits the compile error:发出编译错误:

Error:(102, 17) TS2339: Property 'children' does not exist on type 'MyProps'.错误:(102, 17) TS2339:“MyProps”类型上不存在属性“children”。

I guess this is because there's really no way for the compiler to know that a vanilla function is going to be given children in the props argument.我想这是因为编译器真的没有办法知道在 props 参数中将给一个普通的 function 提供children

So the question is how should we use children in a stateless functional component in TypeScript?那么问题来了,我们应该如何在 TypeScript 中的无状态功能组件中使用 children?

I could go back to the old way of MyProps extends React.Props , but the Props interface is marked as deprecated , and stateless components don't have or support a Props.ref as I understand it.我可以 go 回到MyProps extends React.Props的旧方式,但是Props接口被标记为 deprecated ,并且据我所知,无状态组件没有或不支持Props.ref

So I could define the children prop manually:所以我可以手动定义children道具:

interface MyProps {
  children?: React.ReactNode;
}

First: is ReactNode the correct type?第一: ReactNode是正确的类型吗?

Second: I have to write children as optional ( ? ) or else consumers will think that children is supposed to be an attribute of the component ( <MyStatelessComponent children={} /> ), and raise an error if not provided with a value.第二:我必须将孩子写为可选( ? ),否则消费者会认为children应该是组件的属性<MyStatelessComponent children={} /> ),如果没有提供值,则会引发错误。

It seems like I'm missing something.好像我错过了什么。 Can anyone provide some clarity on whether my last example is the way to use stateless functional components with children in React?任何人都可以澄清我的最后一个例子是否是在 React 中使用无状态功能组件和子组件的方法吗?

You can use React.PropsWithChildren<P> type for your props:你可以为你的道具​​使用React.PropsWithChildren<P>类型:

interface MyProps { }

function MyComponent(props: React.PropsWithChildren<MyProps>) {
  return <div>{props.children}</div>;
}

React 16.8 Update: Since React 16.8, the names React.SFC and React.StatelessComponent are deprecated. React 16.8 更新:自 React 16.8 起,名称React.SFCReact.StatelessComponent已弃用。 Actually, they have become aliases for React.FunctionComponent type or React.FC for short.实际上,它们已经成为React.FunctionComponent类型或React.FC别名。

You would use them the same way though:你会以同样的方式使用它们:

const MyStatelessComponent : React.FunctionComponent<MyProps> = props =>
    <div>
        <p>{props.propInMyProps}</p>
        <p>{props.children}</p>
    </div>

Before React 16.8 (Older):在 React 16.8(旧版)之前:

For now, you can use the React.StatelessComponent<> type, as:现在,您可以使用React.StatelessComponent<>类型,如下所示:

const MyStatelessComponent : React.StatelessComponent<{}> = props =>
    <div>{props.children}</div>

What I have added there is setting the return type of the component to React.StatelessComponent type.我在那里添加的是将组件的返回类型设置为React.StatelessComponent类型。

For a component with your own custom props (like MyProps interface):对于具有您自己的自定义道具的组件(如MyProps接口):

const MyStatelessComponent : React.StatelessComponent<MyProps> = props =>
    <div>
        <p>{props.propInMyProps}</p>
        <p>{props.children}</p>
    </div>

Now, props has got the children property as well as those from MyProps interface.现在, props已经获得了children属性以及来自MyProps接口的属性。

I checked this in typescript version 2.0.7我在打字稿版本 2.0.7 中检查了这个

Additionally, you can use React.SFC instead of React.StatelessComponent for brevity.此外,为了简洁起见,您可以使用React.SFC代替React.StatelessComponent

Simpler answer: Use ReactNode :更简单的答案:使用ReactNode

interface MyProps {
  children?: React.ReactNode
}

If children is optional or not (ie having ? or not) depends on your component. children是否可选(即有?或没有)取决于您的组件。 The ? ? is the most concise way to express that, so nothing wrong with that.是最简洁的表达方式,所以没有错。

On history: This was not necessarily the correct answer back when originally asked: The type ReactNode was added in (almost) its current form in March 2017 by this pull request only, but almost everyone reading this today should be on a modern enough version of React.关于历史:当最初被问到时,这不一定是正确的答案: ReactNode类型ReactNode在 2017 年 3 月通过此拉取请求以(几乎)其当前形式添加,但几乎今天阅读本文的每个人都应该使用足够现代的版本反应。

Lastly, about passing children as "attribute" (which, in React lingo, would be passing it as "prop", not attribute): It is possible, but in most cases reads better when passing JSX children:最后,关于将children作为“属性”传递(在 React 术语中,将其作为“prop”而不是属性传递):这是可能的,但在大多数情况下,在传递 JSX 子项时读起来更好:

<MyComponent>
  <p>This is part of the children.</p>
</MyComponent>

reads more easily than比阅读更容易

<MyComponent children={<p>This is part of the children.</p>} />

You can just add children to the component and if it is connected to a container that is all you need.您可以将子组件添加到组件中,如果它已连接到您所需要的容器。

const MyComponent = ({ 
   children  
}) => {
  return <div>{children}</div>

}

Make sure your file is.tsx not.ts确保您的文件是.tsx 而不是.ts

You can use你可以使用

interface YourProps { }
const yourComponent: React.SFC<YourProps> = props => {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Typescript 将 React 子组件限制为另一个功能组件? - How to use Typescript to restrict React component children to another functional component? 如何在无状态功能组件中访问 props.children? - How to access props.children in a stateless functional component in react? 我应该如何在 React 中使用 Typescript 声明无状态功能组件? - How should I declare a Stateless Functional Component with Typescript in React? 无状态功能组件 - React - Stateless Functional Component - React React - 如何确定组件是否无状态/功能? - React - how to determine if component is stateless/functional? 如何为 React 无状态功能组件模拟 api? - How to mock an api for a React stateless functional component? 如何在React Native的无状态功能组件中扩展Native组件的props TypeScript接口? - How to extend a native's component's props TypeScript interface in a stateless, functional component in React Native? 带有 props.children 的 Typescript React 功能组件 - Typescript React Functional Component with props.children 使用TypeScript创建一个接受数组的React无状态功能组件 - Using TypeScript To Create A React Stateless Functional Component That Accepts Array Typescript + React,从无状态功能组件渲染数组 - Typescript + React, rendering an array from a stateless functional component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM