Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

reactjs - 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:

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'.

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.

So the question is how should we use children in a stateless functional component in TypeScript?

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.

So I could define the children prop manually:

interface MyProps {
  children?: React.ReactNode;
}

First: is ReactNode the correct type?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use React.PropsWithChildren<P> type for your props:

interface MyProps { }

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...