首页 > 解决方案 > 当添加或删除子/孙组件时,如何在 React 中判断?

问题描述

componentDidUpdate在 React 中,我可以通过将代码放在生命周期方法中来在组件更新时执行一些代码。就我而言,我需要区分两种类型的更新。第一种是仅现有组件上的 props 发生变化(不会添加或删除 DOM 元素,但现有元素的属性/内容可能会更改)。第二个是添加/删除新的子组件时(将添加或删除 DOM 元素)。

考虑下面的伪代码;我希望在具有nameof的组件list删除其一个子组件时执行一个函数,但不是在任何子组件的active道具发生更改时执行。这只是一个通用示例,并不是我想要做的唯一事情,否则我可以针对这种特定情况定制我的解决方案。

<Module>
  <Component name='list' />
    <Component active={true} />
    <Component active={false} />
    <Component active={false} />
  </Component>
</Module>

理想情况下,我的解决方案应该只影响ModuleReact 组件,而不需要对 Component React 组件进行任何更改,例如:

export default class Module extends React.Component {
  componentDidUpdate() {
    if ('component tree has been altered') {
      // do something
    }
    else {
      // do something else
    }
  }

  ...
}

我考虑获取props.children.length值并将其存储为状态,然后如果值在渲染之间发生变化,我知道元素已被添加/删除,但我认为这在添加/删除大子组件时不起作用,只有直接子组件。

我觉得可能有一个使用上下文 API 的解决方案,但我不太确定它会是什么。

标签: javascriptreactjs

解决方案


创建两个在子组件挂载或卸载时调用的函数,将函数作为道具传递给子组件。

class ParentComponent extends Component {
  childMounted() {
    console.log('child mounted')
  }
  childUnmounted() {
    console.log('child un-mounted')
  }
  render() {
    return(
      <div>
        <ChildComponent mounted={this.childMounted} unmounted={this.childUnmounted} />
      </div>
    )
  }
}

在子组件中只需调用生命周期方法中的函数。

class ChildComponent extends Component {
  componentDidMount() { this.props.childMounted() }
  componentWillUnmount() { this.props.unmounted() }
  render() { return null; }
}

推荐阅读