2019 年的 HOC 与克隆元素



我了解到,只有在类逻辑相同时,你才可以使用 HOC 来修改渲染函数。我尝试自己做,并想出了一个使用this.props.children和cloneElement的解决方案。

我在 StackOverFlow 上搜索以找到两者之间的差异,但关于这一点的唯一问题是从 2016 年开始,此后 React 发生了变化。我想知道其中一个是否存在性能问题,以及在 2019 年什么被认为是"最佳实践">

这是克隆元素:

<Counter>
<ButtonCounter />
</Counter>
<Counter>
<KeyStrokesCounter />
</Counter>
export default class Counter extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
updateCounter = () => {
this.setState(prev => ({
counter: prev.counter + 1
}));
};
render() {
return (
<React.Fragment>
{React.cloneElement(this.props.children, {
clickHandler: this.updateCounter,
counter: this.state.counter
})}
</React.Fragment>
);
}
}
export default class ButtonCounter extends Component {
constructor(props) {
super(props);
console.log('ButtonCounter created lol');
}
render() {
return (
<div>
<button onClick={this.props.clickHandler}>
Clicked {this.props.counter} times
</button>
</div>
);
}
}

和 HOC:

<Button />
<InputKeyStroke />
const CounterComponent = OgComp => {
class NewComp extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 42
};
}
incrementCounter = () => {
this.setState(prev => ({
counter: prev.counter + 1
}));
};
render() {
return (
<OgComp
evtHandler={this.incrementCounter}
counter={this.state.counter}
/>
);
}
}
return NewComp;
};
export default CounterComponent;
export default CounterComponent(
class Button extends React.Component {
constructor(props) {
super(props);
console.log('RCONST BUTTON');
}
render() {
return (
<button onClick={this.props.evtHandler}>
Clicked {this.props.counter} times
</button>
);
}
}
);

有没有最好的方法可以做到这一点?在每个克隆元素事件期间不会调用构造函数。

这并不能回答你的问题,但这是我为 cloneElement VS 渲染道具找到的基准: https://gist.github.com/nemoDreamer/21412b28dc65d51e2c5c8561a8f82ce1

最新更新