2

我有 3 个组件。一个父组件和两个子组件 (A,B)。第一个子组件 A 有一个触发父组件功能的按钮。父组件有一个开关来显示或不显示子组件 B。如果子组件 B 应该是可见的,它就会被挂载。从 parent 调用的函数 child A 现在执行组件 B 中的函数。

我试图通过在子组件 B 上提供一个 ref 属性来实现它。但是由于它没有安装的一个很好的理由是 initthis.refs是空的。如何在不安装所有可能的子组件 B(或以后的 C、D、E)的情况下实现这一点。

重要的是子 A 中的 onClick 事件始终触发引用的事件。

这是一个快速草稿:在此处输入图像描述

谁能给我一个提示来解决我的逻辑问题?

4

1 回答 1

1

The following line:

The function child A called from parent now executes a function in component B.

is strange/ and a no-go area with react: A parent cannot (should not) directly call a function inside a child component.
A parent can (should) pass a prop to the child, and then the child can initiate its own function.

If I understand correctly, you want to execute the function inside child B to execute when a) component A is clicked AND b) component B is mounted

You can achieve this as follows:

  • add a state parameter inside parent, e.g. this.setState(childAClicked: true), most likely inside the callback function inside the parent, called by child A.
  • pass this parameter to child B, e.g. <ChildB clickedA = {this.state.childAClicked} />
  • inside child B, add a componentDidMount() lifecycle method, which checks this.props.clickedA, and if true, executes your function inside child B
  • if you want to execute the function also after updates to child B, add the same check inside a componentDidUpdate() lifecycle method

If you want to execute the function ONLY inside one of the components B, C, D, based on some other parameter, you add this parameter as well to your parent's state, and pass it to other B,C and D components too.

于 2016-04-18T20:34:17.850 回答