检查一个组件是另一个组件 ReactJS 的子组件还是祖先组件 [英] check if a component is a child or ancestor of another component ReactJS

查看:34
本文介绍了检查一个组件是另一个组件 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆