gpt4 book ai didi

javascript - react HOC : render hijacking with functional components

转载 作者:行者123 更新时间:2023-12-05 08:08:28 26 4
gpt4 key购买 nike

来自 this blog article ,组件的渲染可以这样改变:

function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
const elementsTree = super.render()
let newProps = {};
if (elementsTree && elementsTree.type === 'input') {
newProps = {value: 'may the force be with you'}
}
const props = Object.assign({}, elementsTree.props, newProps)
const newElementsTree = React.cloneElement(elementsTree, props, elementsTree.props.children)
return newElementsTree
}
}
}

这似乎只有在传递的组件本身是类组件时才有效。

如何编写相同的代码以使其适用于功能组件?

最佳答案

我相信您可以像这样将包装器中的 Prop 直接传递给功能组件:

const jediEnhancer = (FunctionalComponentToWrap) => {
return class jediEnhancer extends React.Component {
constructor(props){
super(props);

this.state = {
forceIsWithUser: false
};

this.awakenTheForce = this.awakenTheForce.bind(this);

awakenTheForce(){
this.setState({forceIsWithUser: true});
}

render(){
return <FunctionalComponentToWrap awakenTheForce={this.awakenTheForce} {...this.props} />
}
}
}

关于javascript - react HOC : render hijacking with functional components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49405189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com