首页 > 解决方案 > 如何从无状态父级访问子类组件中的函数?

问题描述

我有一个带有初始值对象的 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 来访问子组件的所有功能。

标签: javascriptreactjsreact-reduxreact-hooks

解决方案


最好的方法是使用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
  }
  ....
}

推荐阅读