check if a component is a child or ancestor of another component ReactJS

对着背影说爱祢 提交于 2019-12-08 03:12:12

问题


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?


回答1:


The parent can define a function in the context, Children can then call this function:

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!')
},


来源:https://stackoverflow.com/questions/39673998/check-if-a-component-is-a-child-or-ancestor-of-another-component-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!