Reactjs 如何用生命周期方法扩展外部反应元件?
我想将componentDidUpdate()实现添加到现有的外部组件中 例如,假设我希望组件XYZ在更新时将信息记录到控制台,并从XYZ调用另一个方法Reactjs 如何用生命周期方法扩展外部反应元件?,reactjs,Reactjs,我想将componentDidUpdate()实现添加到现有的外部组件中 例如,假设我希望组件XYZ在更新时将信息记录到控制台,并从XYZ调用另一个方法 const updatable = () => WrappedComponent => { return class LoadingHOC extends Component { componentDidUpdate() { console.log('u
const updatable = () => WrappedComponent => {
return class LoadingHOC extends Component {
componentDidUpdate() {
console.log('updated');
//cannot call super.iWantToCallThisMethod();
}
render() {
<WrappedComponent {...this.props} />
}
};
};
我可能可以从技术上扩展XYZ并添加componentDidUpdate()
但我们应该避免任何不同于组件的继承(如果上述方法有效,我还没有尝试过,因为我不想使用继承)
另一个选项是使用HOC并使用XYZ作为WrappedComponent,但我不能从XYZ调用方法
const updatable = () => WrappedComponent => {
return class LoadingHOC extends Component {
componentDidUpdate() {
console.log('updated');
//cannot call super.iWantToCallThisMethod();
}
render() {
<WrappedComponent {...this.props} />
}
};
};
const updateable=()=>WrappedComponent=>{
返回类LoadingHOC扩展组件{
componentDidUpdate(){
console.log('updated');
//无法调用super.iWantToCallThisMethod();
}
render(){
}
};
};
如何实现它?如果不更改初始组件源,就无法直接实现这一点。这就是为什么大多数组件库在props中公开所有可能的事件和处理程序 我可能可以从技术上扩展XYZ并添加componentDidUpdate()
您可以尝试这种方法,如果实现正确,应该不会出现问题,但您必须知道,只有当外部组件是类组件时,这种方法才会起作用,如果源组件有自己的实现,您可能还需要调用
super.componentdiddupdate
。在这方面,一个可能的解决方案是使用
REF提供了一种访问DOM节点或反应在渲染方法中创建的元素的方法
类UpdateableXYZ扩展组件{
建造师(道具){
超级(道具);
//创建引用。
this.xyzRef=React.createRef();
}
componentDidUpdate(){
log('updateablexyzupdated');
//访问引用的方法
this.xyzRef.current.iWantToCallThisMethod();
}
render(){
//将引用绑定到组件实例
返回
}
}
请不要忘记将答案标记为“已接受”。这将向用户显示与此特定答案帮助解决您的问题相同的问题。
class UpdatableXYZ extends Component {
constructor(props) {
super(props);
// Create the reference.
this.xyzRef = React.createRef();
}
componentDidUpdate() {
console.log('UpdatableXYZ updated');
// Access the method of the reference
this.xyzRef.current.iWantToCallThisMethod();
}
render() {
// Bind the reference to the component instance
return <XYZ ref={this.xyzRef} />
}
}