【问题标题】:Why React.Children.only?为什么选择 React.Children.only?
【发布时间】:2018-07-28 00:22:26
【问题描述】:

反应大师的快速问题;)

React.Children.only 是它的顶级 api 之一,react-redux (<Provider />) 和 React Router (<Router />) 非常常用来将 store/router 作为上下文注入,这背后的原因是什么,为什么不简单地return props.children?好像和 JSX 有关系?

编辑:请不要解释什么是React.Children.only,我问的是为什么使用它而不是props.children,这似乎更强大/灵活。

【问题讨论】:

  • 文档似乎不言自明 - 一种验证您只有一个孩子的好方法
  • 原因是你为什么要定义一个只有一个孩子的界面,在应用程序的角度来看,将 props.children 作为一个元素数组返回是很常见的,对吧?

标签: reactjs react-router react-redux children


【解决方案1】:

正如docs中指出的那样

验证 children 只有一个子元素(一个 React 元素)并返回它。否则这个方法会报错。

那么现在为什么它比仅使用 props.children 更有帮助?

主要原因是它抛出了一个错误,从而停止了整个开发流程,所以你不能跳过它。

这是一个方便的实用程序,它强制执行特定且只有一个孩子的规则。

当然,您可以使用propTypes,但这只会在控制台中发出警告,您可能会错过。

React.Children.only 的一个用例可以是强制执行应由一个逻辑子组件组成的特定声明性接口:

class GraphEditorEditor extends React.Component {
  componentDidMount() {
    this.props.editor.makeEditable();
    // and all other editor specific logic
  }

  render() {
    return null;
  }
}

class GraphEditorPreview extends React.Component {
  componentDidMount() {
    this.props.editor.makePreviewable();
    // and all other preview specific logic
  }

  render() {
    return null;
  }
}

class GraphEditor extends React.Component {
  static Editor = GraphEditorEditor;
  static Preview = GraphEditorPreview;
  wrapperRef = React.createRef();

  state = {
    editorInitialized: false
  }

  componentDidMount() {
    // instantiate base graph to work with in logical children components
    this.editor = SomeService.createEditorInstance(this.props.config);
    this.editor.insertSelfInto(this.wrapperRef.current);

    this.setState({ editorInitialized: true });
  }

  render() {
    return (
      <div ref={this.wrapperRef}>
        {this.editorInitialized ?
          React.Children.only(
            React.cloneElement(
              this.props.children, 
              { editor: this.editor }
            )
          ) : null
        }
      </div>
    );
  }
}

可以这样使用:

class ParentContainer extends React.Component {
  render() {
    return (
      <GraphEditor config={{some: "config"}}>
        <GraphEditor.Editor> //<-- EDITOR mode
      </GraphEditor>
    )
  }
}

// OR

class ParentContainer extends React.Component {
  render() {
    return (
      <GraphEditor config={{some: "config"}}>
        <GraphEditor.Preview> //<-- Preview mode
      </GraphEditor>
    )
  }
}

希望这有帮助。

【讨论】:

  • 感谢您的回答,我认为您指出限制只有一个孩子的原因可以由 PropTypes.element 处理,propTypes 并不强制执行运行时安全,但这是打字稿/流程的另一个主题.我不认为它与渲染道具有任何关系,因为 redux 提供者和 react-router 的路由器都没有使用这个,但他们确实使用了 React.Children.only。无论如何,谢谢!
  • @Xlee 我并没有指出这些项目确实使用了渲染道具,但确实有很多。这是一个例如github.com/chenglou/react-radio-group/blob/…
  • @Xlee 关于执行,这里是 react-router 中的提交,明确概述了目的github.com/ReactTraining/react-router/commit/…
  • 我的意思是我个人非常喜欢渲染道具,因为它很酷而且很有用,但最后你会发现它们只是众多组件模式中的一种,基于用例具有优缺点。关于该提交,它只是告诉 React.Children.only 可用于强制执行单个孩子,但这并不意味着它是为此而设计的。我的问题是,为什么 redux 提供商强制其用户只传递一个孩子,而您却在告诉我他们是如何做到这一点的,我已经知道了,对吧?
  • @Xlee 不,我要说的是,他们使用React.Children.only 是因为他们想要处理单个 React.Element 而不是数组。这是一个简单的保障措施,显然,他们不想处理传递数组时的逻辑。这是从他们的代码和React.Children.only 本身的定义中得出的唯一合乎逻辑的解释。如果您寻求任何隐藏的含义,我认为您最好的选择是与创作者一起,直接问丹,让我们都知道:) 祝你好运。
【解决方案2】:

Before React 16,组件的渲染方法无法返回元素数组。当实现一个没有引入任何自己的标记的组件时,你别无选择,只能接受一个孩子:

// We have to ensure that there's only one child, because returning an array
// from a component is prohibited.
const DisplayIf = ({children, condition}, {uniforms}) =>
    condition(uniforms) ? Children.only(children) : nothing;
DisplayIf.contextTypes = BaseField.contextTypes;

现在您可以简单地return props.children,要求调用者在数组元素中包含keys,或者return &lt;&gt;{props.children}&lt;/&gt;,使用Fragment 来避免返回数组:

const DisplayIf = ({children, condition}, {uniforms}) =>
    condition(uniforms) ? <>{children}</> : nothing;
DisplayIf.contextTypes = BaseField.contextTypes;

【讨论】:

  • 请注意,这个&lt;DisplayIf&gt;&lt;SomeComponent /&gt;&lt;/DisplayIf&gt; 是个坏主意——SomeComponent 总是被渲染,如果条件不满足,它就会被 DisplayIf 丢弃。因此,如果 SomeComponent 的渲染成本很高,或者在预期不显示时会产生错误,这可能会导致问题。
猜你喜欢
  • 2017-11-16
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2013-04-22
  • 1970-01-01
相关资源
最近更新 更多