我想将componentDidUpdate()实现添加到现有的外部组件中。
例如,假设我希望组件XYZ在更新信息时将信息记录到控制台,并从XYZ调用另一个方法。
我可能可以从技术上扩展XYZ并添加componentDidUpdate()
import {ZYZ} from 'external-lib'
class UpdatableXYZ extends XYZ{
componentDidUpdate() {
console.log('UpdatableXYZ updated')
super.iWantToCallThisMethod();
}
render() {
super.render();
}
}
但是我们应该避免任何不同于Component的继承(如果上面的方法可行,请不要尝试,因为我不想使用继承)。
其他选项将使用HOC并将XYZ用作WrappedComponent,但是我无法从XYZ调用方法。
const updatable = () => WrappedComponent => {
return class LoadingHOC extends Component {
componentDidUpdate() {
console.log('updated');
//cannot call super.iWantToCallThisMethod();
}
render() {
<WrappedComponent {...this.props} />
}
};
};
我如何实现?
答案 0 :(得分:1)
没有改变原始组件源的简单方法。这就是为什么大多数组件库都在props中公开所有可能的事件和处理程序的原因。
我可能可以从技术上扩展XYZ并添加componentDidUpdate()
您可以尝试一下,并且如果正确实现,应该不会有问题,但是您必须意识到,只有在外部组件是类组件的情况下,这才起作用,而且您可能需要调用{{1} },如果源组件具有相同的实现。
答案 1 :(得分:1)
使用Refs是可能的并且在这方面最受青睐的解决方案。
引用提供了一种访问DOM节点或在render方法中创建的 React元素的方法。
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} />
}
}