javascript - 当添加或删除子/孙组件时,如何在 React 中判断?
问题描述
componentDidUpdate
在 React 中,我可以通过将代码放在生命周期方法中来在组件更新时执行一些代码。就我而言,我需要区分两种类型的更新。第一种是仅现有组件上的 props 发生变化(不会添加或删除 DOM 元素,但现有元素的属性/内容可能会更改)。第二个是添加/删除新的子组件时(将添加或删除 DOM 元素)。
考虑下面的伪代码;我希望在具有name
of的组件list
删除其一个子组件时执行一个函数,但不是在任何子组件的active
道具发生更改时执行。这只是一个通用示例,并不是我想要做的唯一事情,否则我可以针对这种特定情况定制我的解决方案。
<Module>
<Component name='list' />
<Component active={true} />
<Component active={false} />
<Component active={false} />
</Component>
</Module>
理想情况下,我的解决方案应该只影响Module
React 组件,而不需要对 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 的解决方案,但我不太确定它会是什么。
解决方案
创建两个在子组件挂载或卸载时调用的函数,将函数作为道具传递给子组件。
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; }
}
推荐阅读
- shopify - 跟踪自定义变体的库存
- swift - 在一个预期会在 swift 中返回“UITableViewCell”的函数中出现错误,如 Missing return
- python - 将列表转换为字典,其中每个键嵌套在下一个键下
- r - 在 R 中获取具有多个变量的 PK 的唯一列(postgreSQL etl)
- r - ggplot,条件填充 geom_point
- python - 未能找到可以处理输入的数据适配器:
, - r - R Markdown - 如何更改文本输出的大小 (PDF)
- android - 如何实现自定义上下文动作模式?
- c# - 将查看收件人的需求添加到模板
- javascript - React 脚本标签用法