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
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>
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. - Both Mixin and HOC use Static composition.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.