【问题标题】:Rendering props to Wrapped Component when using HOC in react在反应中使用 HOC 时将道具渲染到包装组件
【发布时间】:2018-12-09 13:02:18
【问题描述】:

我在查看高阶组件的反应文档时偶然发现了一个示例,您可以在其中为特定组件记录道具

function logProps(WrappedComponent) {
return class extends React.Component {
    componentWillReceiveProps(nextProps) {
      console.log('Current props: ', this.props);
      console.log('Next props: ', nextProps);
    }
    render() {
      // Wraps the input component in a container, without mutating it. Good!
      return <WrappedComponent {...this.props} />;
    }
  }
}

当你渲染组件时插入和插入有区别

{...this.props} 

和

{props.children}

它们本质上都会将给定的道具返回给组件,是否有最佳实践或特定用例何时比另一个更好?

来自关于 props.children 的 react 文档

 you can use props.children on components that represent ‘generic boxes’ and that ‘don’t know their children ahead of time’. 

对我来说,这似乎与 {...this.props}

中的用例相同

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    {...this.props} 和props.children 用于实现不同的目标。

    {...this.props} 被使用,所以所有给这个特定组件的道具都是spread 到另一个。以docs为例:

    function App1() {
      return <Greeting firstName="Ben" lastName="Hector" />;
    }
    
    function App2() {
      const props = {firstName: 'Ben', lastName: 'Hector'};
      return <Greeting {...props} />;
    }
    

    这两种情况的结果相同。因此,spread 是从 HOC 传递道具的最佳方法。

    props.children 另一方面用于将子组件传递给另一个组件。这是 React 分配的一个特定的prop,您无法在属性中显式找到它。这个道具存在于组件的开始和结束标签内。另一个来自docs的例子:

    <MyComponent>Hello world!</MyComponent>
    
    // Can be used in the component as:
    function MyComponent() {
      return (
        <div>{props.children}</div>
      );
    }
    

    在这里,MyComponent 将向 DOM 发出 &lt;div&gt;Hello World&lt;/div&gt;。

    【讨论】:

    • 准确答案,感谢您的澄清
    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2020-03-10
    • 2020-04-16
    • 2017-12-02
    • 2021-01-19
    相关资源
    最近更新 更多