我正在为我的各种 React 组件构建一个高阶组件。在这个 HOC 中,我需要访问 child 的方法并调用它们。我该怎么做?
示例 HOC:
export default function withHOC(Component) {
return class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
if (Component.someFunction) {
Component.someFunction()
}
}
render() {
return <Component {...this.props} />;
}
};
}
示例组件:
class App extends React.Component {
someFunction() {
console.log("something done here, for example setState")
}
render() {
return (
<div></div>
);
}
}
// then it's used like this
export default withHOC(App)
我知道在某些情况下,像这样解决它甚至可能没有意义,但例如框架 Next.js 可以用它的 getInitialProps 函数做类似的事情。
最佳答案
既然你想调用HOC的componentDidMount中的子组件方法,一个更好的选择是确实调用组件本身的componentDidMount
中的方法,这样可以解决当子组件没有功能,或者它由多个 HOC 组成,例如
export default function withHOC(Component) {
return class extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Component {...this.props} />;
}
};
}
class App extends React.Component {
componentDidMount() {
this.someFunction();
}
someFunction() {
console.log("something done here, for example setState")
}
render() {
return (
<div></div>
);
}
}
但是如果你仍然想在子组件中调用该函数,你可以使用 refs(但是如果 App 组件由其他 HOC 组成,这将不起作用)
export default function withHOC(Component) {
return class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.cmp.someFunction();
}
render() {
return <Component ref={(ref) => this.cmp = ref} {...this.props} />;
}
};
}
class App extends React.Component {
someFunction() {
console.log("something done here, for example setState")
}
render() {
return (
<div></div>
);
}
}
关于javascript - 在 HOC 中访问 React 组件的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054368/