简体   繁体   English

如何创建一个元素并在反应中使用它对 append 子元素的引用?

[英]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.我正在尝试在父组件上创建 html 元素反应并访问子组件内的组件 div,然后我可以 append 子组件中的 div 中的新元素。

After many attempts I wasn't able to fix props.canvasDivElement.current = null on the child constructor.经过多次尝试,我无法在子构造函数上修复 props.canvasDivElement.current = null 。

I've tried to do this using REF and without refs... No luck so far.我尝试过使用 REF 而没有 refs 来做到这一点......到目前为止还没有运气。

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.看起来你试图绕过 React 的基本原则来解决 React 提供其他工具的问题。 The React way of communicating between a child and a parent is to pass a callback function to the child.子与父之间通信的 React 方式是向子传递一个回调 function。 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.新手错误,在渲染之前,元素将始终为 null。 I've changed the line bellow to the componentDidMount event:我已将下面的行更改为 componentDidMount 事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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