Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

reactjs - React Access parent component name

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...