简体   繁体   English

在使用HOC进行反应时向包装组件渲染道具

[英]Rendering props to Wrapped Component when using HOC in react

I was looking at the react documentation for Higher-Order Components and I stumbled upon an example where you can log props, for a specific component 我在查看高阶组件的react文档时,偶然发现了一个示例,可以在其中记录特定组件的道具

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

when you render the component is there a difference between inserting 当您渲染组件时,插入之间有区别

{...this.props} 

and

{props.children}

they would both essentially return the given props to the component, is there a best practice or a specific use case where when is better than the other? 他们基本上都会将给定的道具返回给组件,是否存在最佳实践或特定用例,其中何时比另一个更好?

From the react docs about props.children 来自关于props.children的反应文档

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

to me this seems like the same use case as in {...this.props} 对我来说,这似乎与{... this.props}中的用例相同

{...this.props} and props.children are used for achieving different objectives. {...this.props}props.children用于实现不同的目标。

{...this.props} is used so that all the props given to this specific component are spread onto another. {...this.props} ,以便将赋予该特定组件的所有道具散布到另一个道具上。 Taking an example from the docs : docs为例:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

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

These two cases have the same results. 这两种情况具有相同的结果。 So, spread is best approach for passing on props from an HOC. 因此, spread是从HOC传递道具的最佳方法。

props.children on the other hand is used to pass on children to another component. 另一方面, props.children用于将子级传递给另一个组件。 This is one specific prop that React assigns that you cannot explicitly find among attributes. 这是React分配的一种具体prop ,您无法在属性中明确找到。 This prop is present inside the opening and closing tag of a component. 该道具位于组件的打开和关闭标签内。 Another example from docs : 来自docs的另一个示例:

<MyComponent>Hello world!</MyComponent>

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

Here, MyComponent will emit <div>Hello World</div> to the DOM. 在这里, MyComponent将向DOM发出<div>Hello World</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM