将元素插入REACT子元素

问题描述 投票:0回答:1

我正在用react渲染一个图表,我想在该图表的标题中添加一个元素。不幸的是,我使用的是共享图表组件,并且很难对组件进行重大修改。

我尝试使用refs;但是,我在弄清楚如何实际将虚拟dom元素附加为子元素时遇到困难。

特定图表类别:

class ChartWithInfo extends React.Component {
    constructor(props){
        super(props);
        this.chartWrapperElement = React.createRef();        
    } 

    componentDidMount() {
        const infoInsertion = (
            <div>
               <IconButton/>
            </div>
        )
        this.chartWrapperElement.current.insertBefore(infoInsertion, this.chartWrapperElement.current.firstChild);
    }

    render() {
        return (
            <GenericChart
                variables={this.props.variables}
                ref={this.chartWrapperElement}
            />
        );
    }
}

通用图表类

export default class EmbeddedChart extends PureComponent {
    // Random methods //
    render() {
        return (
            <div ref={this.props.ref} id={'chartDiv'}>
                Chart
            </div>
        );
    }
}

预期结果本质上是:

<div id='chartDiv'>
   <IconButton/>
</div>


What is the most react way to do this? Am I missing something with refs?
javascript reactjs dom refs
1个回答
0
投票

React适用于组件,如果您遵循关注点和组件体系结构的分离。您可以隔离所有组件和单个可重用组件。单独创建按钮组件,然后将其导入其他任何地方。分别绑定您的事件和业务逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.