【问题标题】:check if a component is a child or ancestor of another component ReactJS检查一个组件是另一个组件 ReactJS 的子组件还是祖先组件
【发布时间】:2017-02-02 02:16:38
【问题描述】:
我正在创建一个具有未知数量的子级和祖先的 ReactJS 组件,当某个事件发生在其中一个祖先上时,父组件应该知道它。我的第一种方法是使用 redux 并通过 redux 操作发送子组件,然后主父组件将被警告并检查发送的组件是否是其祖先之一。
但是,如果另一个组件是它的祖先之一,父 reactJS 组件是否可以通过某种方式知道?
【问题讨论】:
标签:
reactjs
components
redux
children
ancestor
【解决方案1】:
父母可以在上下文中定义一个函数,然后孩子可以调用这个函数:
家长:
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!')
},