简体   繁体   English

React HOC和render-props模式之间的区别?

[英]The difference between React HOC and render-props pattern?

I have just learned these two patterns. 我刚刚学习了这两种模式。 I'm quite confused about how to use these pattern correctly. 我对如何正确使用这些模式感到困惑。

I created a component and try to apply these patterns. 我创建了一个组件并尝试应用这些模式。 Everything works the same. 一切都一样。

Source code: https://codesandbox.io/s/n504v2njr4 源代码: https : //codesandbox.io/s/n504v2njr4

Render Props pattern 渲染道具模式

class Toggle extends Component {
  state = {
    on: false,
  }

  onToggle = () => {
    this.setState(({ on }) => ({ on: !on}));
  }

  getStateHelper = () => ({
    on: this.state.on,
    toggle: this.onToggle,
  });

  render() {
    return this.props.children(this.getStateHelper())
  }
}

Usage 用法

  <Toggle>
    {({on, toggle}) => (<button onClick={toggle}>{on ? 'On' : 'Off'}</button>)}
  </Toggle>

High Order Component pattern 高阶分量模式

function ToggleHoc(Comp) {
  return class ToggleHocWrap extends Component {
    state = {
      on: false,
    }

    onToggle = () => {
      this.setState(({ on }) => ({ on: !on}));
    }

    getStateHelper = () => ({
      on: this.state.on,
      toggle: this.onToggle,
    });

    render() {
      return (<Comp {...this.getStateHelper()} />)
    }
  }
}

Usage 用法

function TestToggle({ on, toggle }) {
  return (<button onClick={toggle}>{on ? 'On' : 'Off'}</button>)
}

const WithToggle = ToggleHoc(TestToggle);

Please help me!. 请帮我!。 Thank you, guys. 感谢大伙们。

Actually, there are some issues with Mixin as well as HOC, like ghost state and props, Whoever use multiple Mixin and HOC in one component they always need to figure it out who is setting and passing the props and state, - Name collision is one more know issue. 实际上,Mixin和HOC都存在一些问题,例如幻影状态和道具,如果在一个组件中使用多个Mixin和HOC,他们总是需要弄清楚谁在设置和传递道具和状态,-名称冲突是其中之一。更多知道的问题。 - Both Mixin and HOC use Static composition. -Mixin和HOC均使用静态合成。

While render props don't have an above-mentioned issue as it uses the dynamic composition so there is no name collision. 尽管渲染道具没有上述问题,因为它使用动态合成,因此不会发生名称冲突。

for more info please check below mentioned link. 有关更多信息,请检查下面提到的链接。

Check Here 在这里检查

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

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