说我有2个组件:
class A extends Component {
doSomething() {
}
}
class B extends Component {
doSomethingElse() {
}
}
我有一个HOC:
const hoc = Wrapped => {
return class extends Component {
componentDidMount() {
this.wrapped.genericallyCallDosometingAndDsomethingElse()
}
}
render() {
return (
<Wrapped ref={c => this.wrapped = c} {...this.props}/>
)
}
}
我想调用doSomething或doSomething依赖于传入的组件。有没有比在两个组件中调用方法更好的方法?
答案 0 :(得分:0)
您可以同时拥有自我记录功能和统一呼叫的常规功能:
class A extends Component {
doSomething() {
}
genericallyCallDosometingAndDsomethingElse() {
this.doSomething()
}
}
class B extends Component {
doSomethingElse() {
}
genericallyCallDosometingAndDsomethingElse() {
this.doSomethingElse()
}
}
你也可以检查是否存在函数,如果存在则调用:
return class extends Component {
componentDidMount() {
if( typeof this.wrapped.doSomething == 'function' )
this.wrapped.doSomething();
if( typeof this.wrapped.doSomethingElse == 'function' )
this.wrapped.doSomethingElse();
}
}