首页 > 解决方案 > 子组件 componentDidMount() 应该调用不同的方法取决于父组件

问题描述

  class Parent1 extends Component {
    render() {
                return (
                    <Child />
                );
            }
    }
        
  class Parent2 extends Component {
    render() {
            return (
                <Child />
            );
         }
  }

class Child extends Component {
    componentDidMount() {
        // If child component is called from Parent1 component then
        //then It should  getAction1()
        
        // If child component is called from Parent2 component then
        //then It should call getAction2()
    }
    
    render() {
        return(
        //// some jsx code
        );
    }
}

在 Child 组件中, componentDidMount() 应该调用不同的方法取决于调用 Parent 组件。我将如何实现这一目标?如果没有其他条件,是否有可能实现这一目标?

标签: javascriptreactjs

解决方案


一种方法可能是将您的函数作为道具传递给Child.

class Parent1 extends Component {
  render() {
    return (
      <Child getAction={getAction1}/>
    );
  }
}
        
class Parent2 extends Component {
  render() {
    return (
      <Child getAction={getAction2}/>
    );
  }
}

class Child extends Component {
  componentDidMount() {
  // this.props.getAction will be getAction1 or getAction2
  // depending on which was passed
    this.props.getAction() 
  }
    
  render() {
    return(
    //// some jsx code
    );
  }
}

推荐阅读