检查组件是否是另一个组件ReactJS的子代或祖先 [英] check if a component is a child or ancestor of another component ReactJS
问题描述
我正在创建一个具有未知数量的子代和祖先的ReactJS组件,当某个事件发生在祖先之一时,父代组件应该知道这一点。我的第一种方法是使用redux并通过redux操作发送子组件,然后将通知主要父组件,并检查发送的组件是否是其祖先之一。
,但是父对象reactJS组件可以某种方式知道其他组件是否是其祖先之一吗?
I am creating a ReactJS Component with an unknown number of children and ancestors, and when a certain event occurs on one of the ancestors I the parent component should know of it. my first approach is to use redux and send the child component with a redux action, and then main parent componetnts will be alerted and will check if the Componetnt sent was one of its ancestors. but, can a parent reactJS component know in someway if another component is one of its ancestors?
推荐答案
父组件可以在上下文中定义一个函数,然后孩子可以调用此函数:
The parent can define a function in the context, Children can then call this function:
父项:
childContextTypes: {
notifyChange: React.PropTypes.func.isRequired
},
getChildContext () {
return {
notifyChange: (...args) => this.handleChange(...args)
}
},
handleChange (arg) {
console.log(arg + ' bar!')
},
孩子:
contextTypes: {
notifyChange: React.PropTypes.func
},
handleSomething () {
const { notifyChange } = this.context
// safety check if component is used elsewhere
if (notifyChange) notifyChange('foo!')
},
这篇关于检查组件是否是另一个组件ReactJS的子代或祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!