简体   繁体   中英

Requiring a single React child component in TypeScript (TSX)

If I have an interface that overrides and specifies a single child, something like:

interface Props extends React.HTMLProps<HTMLDivElement> {
    children?: React.ReactElement<any>;
}

class MyComponent extends React.Component<Props, {}> {
    // ...
}

IntelliSense correctly shows the single element child prop type, but I can use a component with these props with multiple child components without any errors:

<MyComponent>
  <div>hello</div>
  <div>world</div>
</MyComponent>

This compiles fine with TypeScript 1.8.30.0, but at run time it breaks:

Invariant Violation: ReactDOM.render(): Invalid component element.

It does work with only one <div/> child element, since the component code is written for that scenario. This seems like a bug to me--I expected it to realize that two <div/> elements doesn't match the definition of children . I figured I would ask here first, though, before opening an issue, in case I'm missing something.

Is it possible to require only a single child via this.props.children , or must I add a specific prop?

This worked for me:

export const Example = (props: { children: ReactElement }) => {
  return <div>{props.children}</div>
}

You can find the relevant information below.

Single Child

To quote:

With React.PropTypes.element you can specify that only a single child can be passed to a component as children.

It is possible to enforce only one child.

var MyComponent = React.createClass({
  propTypes: {
    children: React.PropTypes.element.isRequired
  },

  render: function() {
    return (
      <div>
        {this.props.children} // This must be exactly one element or it will warn.
      </div>
    );
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM