您可以對此使用高階元件。我借用this article
function HigherOrderComponent(WrappedComponent) {
return class NewComponent extends React.Component {
constructor() {
super(props)
this.customMethod = this.customMethod.bind(this)
}
customMethod() {
console.log('You called an injected method');
}
render() {
return <WrappedComponent {...this.props} customMethod={this.customMethod} />
}
}
}
這個例子中如何使用自定義的方法:
import HigherOrderComponent from './HigherOrderComponent'
class MyComponent extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.customMethod()
}
render() {
...
}
}
const MutatedComponent = HigherOrderComponent(MyComponent)
const ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(MutatedComponent)
據我所知,你不能覆蓋一個陣營組件的生命週期方法。但是你可以使用HoC注入方法。