javascript - 子组件 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 组件。我将如何实现这一目标?如果没有其他条件,是否有可能实现这一目标?
解决方案
一种方法可能是将您的函数作为道具传递给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
);
}
}
推荐阅读
- r - 在 Docker 中安装 R 包“devtools”时出现问题 - 安装 git2r 时出错
- jquery - 为什么我的 $.post() 不工作而 $.ajax() 工作?
- c - 我的 fork 进程是并行运行还是一个接一个地执行?
- sql-server - TSQL 找出应该在两个日期/时间之间运行的 SSRS 报告
- azure - 需要 Microsoft OAuth2 流程的信息
- expo - expo 中的 Apollo 客户端 useMutation 每次调用都会渲染两次
- python - Beautifulsoup 不显示所有 html 元素
- r - 如何自动将值放入函数中
- python - Python 套接字密码输入
- sql - 如何进行频繁提交,以便我的 sql 删除查询不会超时