reactjs - 为什么选择 React.Children.only?

标签 reactjs react-router react-redux children

向 react 专家提出一个简短的问题;)

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

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

最佳答案

正如 docs 中指出的那样

Verifies that children has only one child (a React element) and returns it. Otherwise this method throws an error.

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

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

这是一个方便的实用程序,它强制执行专门且一个子级的规则。

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

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

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

希望这对您有所帮助。

关于reactjs - 为什么选择 React.Children.only?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837831/

相关文章:

javascript - ForceUpdate 不像我想象的那样工作吗?

javascript - React-router-dom 中重定向的混淆行为

reactjs - 我可以在 React Router Link 上安全地使用 "to"和 "onClick"属性吗?

reactjs - 使用 Tensorflowjs 对上传的图像进行预测时,React 状态总是落后一步

reactjs - @types/prop-types/index 没有默认导出

reactjs - 我需要访问一个单击按钮后弹出的新窗口

reactjs - 将按钮链接到另一个页面

javascript - 高阶组件无法访问包装组件的默认属性

javascript - 如何在 TypeScript 中实现 redux 中间件类

reactjs - 导出 HTTPS=true 和 set HTTPS=true (react) 之间有什么区别?