javascript - 如何从无状态父级访问子类组件中的函数?
问题描述
我有一个带有初始值对象的 redux-store。这个商店将在子组件中的几个地方得到更新。
我创建了一个无状态功能组件作为父级
const Parent = () => {
const store = useSelector(state => state);
const getInitState = () => {
depends on store, it will return an object as initial state for child component
}
let initState = getInitState(); //it has to be let instead of const, it could be changed during useEffect
useEffect(() => {
some initialization on mount
}, [])
return ( // return is simplified here
<Child initState={iniState} />
)
}
export default Parent;
我有一个类子组件,如下所示
class Child extends Component {
state = {
componentState: this.props.initState
}
....
}
export default Child;
我无法修改子组件这是一个非常复杂的组件,其中包含许多我无法处理的子组件。
现在我需要setState
从父组件访问子组件的功能。或者我需要从父母那里改变孩子的状态,有没有办法做到这一点?
是的,我知道应该考虑一个新设计,因为它是反模式的,但我只是想知道我是否可以在当前设置下做到这一点。
谢谢大家。
==================================================== =============
编辑:对于遇到同样问题的人,功能组件不支持构造函数。因此,我对答案进行了简要更正。
定义父级如下
import React, { useRef } from "react";
const Parent = () => {
const childRef = useRef(null);
return (
<Child ref={childRef} />
)
}
export default Parent;
然后您就可以使用 childRef.current 来访问子组件的所有功能。
解决方案
最好的方法是使用react Context,并在父级中设置状态,然后子级使用父级的状态(使用反应钩子比类组件容易)
但在你提到的情况下(我想知道我可以在当前设置下做到这一点)
你可以使用反应refs
:
首先将 ref prop 放在渲染的组件标签中,然后在父组件中使用它来执行在子组件中声明的函数
如下 :
内部父组件:
const Parent = () => {
.
.
.
constructor() {
//create react ref for our component
this.childComponent = React.createRef();
}
callChildFunction() {
// here using refs you can access function in you child refenrenced component
this.childComponent.cuurent.doSomeUpdateStateStuff(newState);
}
return ( // return is simplified here
<Child ref={this.childComponen} initState={iniState} />
)
...
}
和你的孩子:
class Child extends Component {
state = {
componentState: this.props.initState
}
doSomeUpdateStateStuff(state) {
// stuff updating state callled from parent
}
....
}
推荐阅读
- sql - ORA-01422: 精确提取返回的行数多于请求的行数。我可以使用此查询返回表中的所有行吗?
- c# - 不使用 IGrouping 的 ListView 分组
- spring-boot - Spring Boot 2.3.2 server.forward-headers-strategy=framework 重定向到方案 http 而不是 https
- python - 烧瓶 sqlalchemy 不更新行
- html - 如何根据ngFor在Angular中的索引值将组件添加到不同的div?
- javascript - 如何检查 span 元素的内容是否已更改?
- android - 尝试使用 Kotlin 和 onActivityResult 将数据从 Fragment 发送到 Activity
- html - Angular - 无法匹配路线 - 网址段 [已回答]
- keras - 将keras中的conv2d逐帧应用于视频输入
- c# - 下载 .nupkg 的旧版本 (1.9.2.3) 而不是最新版本 (1.9.2.5)