简体   繁体   中英

How to create an element and use its ref to append child elements in react?

I'm trying to create a html element on a parent component on react and access that component div inside a child component, then I can append new elements in the div from the child component.

After many attempts I wasn't able to fix props.canvasDivElement.current = null on the child constructor.

I've tried to do this using REF and without refs... No luck so far.

Any ideas?

The parent component looks like:

import React from "react";
import ReactViewer from "../ReactViewer/ReactViewer";

export default class CanvasWrapper extends React.Component {
    private _divElement: React.RefObject<HTMLDivElement>;

    constructor(props: any) {
        super(props);
        this._divElement = React.createRef<HTMLDivElement>();
    }

    render() {
        return (
            <div>
                <ReactViewer canvasDivElement={this._divElement}></ReactViewer>
            </div>
        );
    }
}

The child component:

import React from "react";

type ReactViewerState = {
};

type ReactViewerProps = {
    canvasDivElement: React.RefObject<HTMLDivElement>;

};

    export default class ReactViewer extends React.Component<ReactViewerProps, ReactViewerState> {
        constructor(props: ReactViewerProps, state: ReactViewerState) {
            super(props, state);
            const newElement = document.createElement('span');
            newElement.innerText = 'element';
            props.canvasDivElement.current!.appendChild(newElement); //current is null
        }

        render() {
            return (
                <div ref={this.props.canvasDivElement} />
            );
        }
    }

It looks like you are trying to circumvent the basic principles of React to solve a problem that React provides other tools for. The React way of communicating between a child and a parent is to pass a callback function to the child. Then the child calls the callback to signal to the parent to update its children.

Rookie mistake, the element will always be null until it renders. I've changed the line bellow to the componentDidMount event:

    props.canvasDivElement.current!.appendChild(newElement);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM