React Access 父组件名称 [英] React Access parent component name

查看:60
本文介绍了React Access 父组件名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在子组件中获取父组件名称以在验证该子组件的属性时显示错误消息.我正在创建一个可重用的组件,因此任何人都可以在他们的组件中使用我的组件.当他们使用我的组件时,我想显示带有父组件名称的警告消息.

是否有特定的方法可以在 react.js 中获取父名称?任何形式的帮助将不胜感激.

解决方案

孩子们可以通过以下方式看到他们创作的上下文:

this._reactInternalInstance._currentElement._owner._instance.__proto__.constructor.name

例如:

import React, { Component } from 'react';类警告扩展组件{使成为() {返回 (<div>{"警告:"+ this._reactInternalInstance._currentElement._owner._instance.__proto__.constructor.name + "有错误."}

);}}导出默认警告;

不要相信这是亲子交流.这就像站在一个房间里,从你所在的地方看到围墙.这不是容器(父级)与您(子级)通信,而是子级感知上下文.

如果您必须使用它,请注意它是 React 内部实例的一部分并且可能会发生变化(请相信它在今天已经足够稳定).

I want to get the parent component name inside the child component to display a error message when validating properties of that child component. I'm creating a reusable component, so anyone can use my component inside their components. When they are using my component I want to display warning messages with the name of the parent component.

Is there a specific method to get parent name in react. Any kind of help would be appreciated.

解决方案

Children can see the context they are composed in through:

this._reactInternalInstance._currentElement._owner._instance.__proto__.constructor.name

For example:

import React, { Component } from 'react';

class Warning extends Component {
    render() {
        return (
            <div>{
                "WARNING: " + this._reactInternalInstance._currentElement._owner._instance.__proto__.constructor.name + " has an error."
            }</div>
        );
    }
}

export default Warning;

Do not believe this is parent-child communication. It is like standing in a room and seeing the containing walls from where you are. This is not the container (parent) communicating to you (child) but rather the child being context-aware.

Use this if you must, however, do note that it is part of React's internal instance and subject to change (do believe it is stable enough as of today).

这篇关于React Access 父组件名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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