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

前端之家收集整理的这篇文章主要介绍了reactjs – 为什么选择React.Children.only?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
反应大师的快速问题;)

React.Children.only是它的顶级api之一,并且很常被react-redux(< Provider />)和React Router(< Router />)用来注入商店/路由器作为上下文,背后的原因是什么这,为什么不简单地返回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的一个用例可以是强制执行特定的声明性接口,该接口应包含一个逻辑子组件:

  1. class GraphEditorEditor extends React.Component {
  2. componentDidMount() {
  3. this.props.editor.makeEditable();
  4. // and all other editor specific logic
  5. }
  6.  
  7. render() {
  8. return null;
  9. }
  10. }
  11.  
  12. class GraphEditorPreview extends React.Component {
  13. componentDidMount() {
  14. this.props.editor.makePreviewable();
  15. // and all other preview specific logic
  16. }
  17.  
  18. render() {
  19. return null;
  20. }
  21. }
  22.  
  23. class GraphEditor extends React.Component {
  24. static Editor = GraphEditorEditor;
  25. static Preview = GraphEditorPreview;
  26. wrapperRef = React.createRef();
  27.  
  28. state = {
  29. editorInitialized: false
  30. }
  31.  
  32. componentDidMount() {
  33. // instantiate base graph to work with in logical children components
  34. this.editor = SomeService.createEditorInstance(this.props.config);
  35. this.editor.insertSelfInto(this.wrapperRef.current);
  36.  
  37. this.setState({ editorInitialized: true });
  38. }
  39.  
  40. render() {
  41. return (
  42. <div ref={this.wrapperRef}>
  43. {this.editorInitialized ?
  44. React.Children.only(
  45. React.cloneElement(
  46. this.props.children,{ editor: this.editor }
  47. )
  48. ) : null
  49. }
  50. </div>
  51. );
  52. }
  53. }

可以像这样使用:

  1. class ParentContainer extends React.Component {
  2. render() {
  3. return (
  4. <GraphEditor config={{some: "config"}}>
  5. <GraphEditor.Editor> //<-- EDITOR mode
  6. </GraphEditor>
  7. )
  8. }
  9. }
  10.  
  11. // OR
  12.  
  13. class ParentContainer extends React.Component {
  14. render() {
  15. return (
  16. <GraphEditor config={{some: "config"}}>
  17. <GraphEditor.Preview> //<-- Preview mode
  18. </GraphEditor>
  19. )
  20. }
  21. }

希望这个对你有帮助.

猜你在找的React相关文章