来自 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/