检查组件是否是另一个组件 ReactJS 的子组件或祖先组件
check if a component is a child or ancestor of another component ReactJS
我正在创建一个具有未知数量的子级和祖先的 ReactJS 组件,当某个事件发生在其中一个祖先上时,我的父组件应该知道它。我的第一种方法是使用 redux 并使用 redux 操作发送子组件,然后主父组件将收到警报并检查发送的组件是否是其祖先之一。
但是,父 reactJS 组件能否以某种方式知道另一个组件是否是其祖先之一?
parent可以在context中定义一个函数,Children可以调用这个函数:
Parent:
childContextTypes: {
notifyChange: React.PropTypes.func.isRequired
},
getChildContext () {
return {
notifyChange: (...args) => this.handleChange(...args)
}
},
handleChange (arg) {
console.log(arg + ' bar!')
},
Child:
contextTypes: {
notifyChange: React.PropTypes.func
},
handleSomething () {
const { notifyChange } = this.context
// safety check if component is used elsewhere
if (notifyChange) notifyChange('foo!')
},
我正在创建一个具有未知数量的子级和祖先的 ReactJS 组件,当某个事件发生在其中一个祖先上时,我的父组件应该知道它。我的第一种方法是使用 redux 并使用 redux 操作发送子组件,然后主父组件将收到警报并检查发送的组件是否是其祖先之一。 但是,父 reactJS 组件能否以某种方式知道另一个组件是否是其祖先之一?
parent可以在context中定义一个函数,Children可以调用这个函数:
Parent:
childContextTypes: {
notifyChange: React.PropTypes.func.isRequired
},
getChildContext () {
return {
notifyChange: (...args) => this.handleChange(...args)
}
},
handleChange (arg) {
console.log(arg + ' bar!')
},
Child:
contextTypes: {
notifyChange: React.PropTypes.func
},
handleSomething () {
const { notifyChange } = this.context
// safety check if component is used elsewhere
if (notifyChange) notifyChange('foo!')
},