【问题标题】:Requiring a single React child component in TypeScript (TSX)在 TypeScript (TSX) 中需要一个 React 子组件
【发布时间】:2016-11-01 04:14:44
【问题描述】:

如果我有一个覆盖并指定单个子级的接口,例如:

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

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

IntelliSense 正确显示了单元素子道具类型,但我可以将具有这些道具的组件与多个子组件一起使用而不会出现任何错误:

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

这可以使用 TypeScript 1.8.30.0 编译,但在运行时会中断:

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

它只适用于一个&lt;div/&gt; 子元素,因为组件代码是为该场景编写的。这对我来说似乎是一个错误——我希望它能够意识到两个&lt;div/&gt; 元素与children 的定义不匹配。不过,我想我会先在这里问一下,然后再打开一个问题,以防我遗漏了什么。

是否可以通过this.props.children 只要求一个孩子,还是必须添加特定的道具?

【问题讨论】:

    标签: reactjs typescript typescript1.8 tsx


    【解决方案1】:

    这对我有用:

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

    【讨论】:

      【解决方案2】:

      您可以在下面找到相关信息。

      Single Child

      引用:

      使用 React.PropTypes.element,您可以指定只能将单个子元素作为子元素传递给组件。

      可以只强制一个孩子。

      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>
          );
        }
      });
      

      【讨论】:

      • 这可能适用于 JSX,但我试图从 TSX 获取 TypeScript 编译器错误。指定 propTypes 是否也向 TS 表明它不应该允许多个孩子?我以前从未见过 propTypes 在 TSX 中改变过任何东西......
      • 不幸的是,TSX 还没有那么聪明。想象一个场景,您将调用一个返回一些内容的函数,这些内容最终会成为MyComponent 中的子项。 TSX 还不能说……。 :) 提交那张罚单可能值得一试,但会很长。
      • 对但是TS知道函数的返回类型和children prop的类型,所以应该可以比较一下,发现不匹配。
      猜你喜欢
      • 1970-01-01
      • 2017-01-31
      • 2021-03-24
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 2017-11-03
      • 2017-01-17
      相关资源
      最近更新 更多