d3.js 无法将d3与react一起使用

g6ll5ycj  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(291)

我想在一个使用react-bootstrap创建的模态窗口中显示一个d3图形。首先,我尝试直接在(非模态)div元素中显示d3圆。我尝试如下:

import "./styles.css";
import React from "react";
import * as d3 from "d3";

export default class App extends React.Component {
  testRef = React.createRef();

  constructor(props) {
    super(props);
    this.changeText = this.changeText.bind(this);
  }

  async changeText() {

    let svg = d3
      .select(this.testRef.current)
      .append("svg")
      .attr("width", 200)
      .attr("height", 200);

    // Add the path using this helper function
    svg
      .append("circle")
      .attr("cx", 100)
      .attr("cy", 100)
      .attr("r", 50)
      .attr("stroke", "black")
      .attr("fill", "#69a3b2");
    // this.testRef.current.innerHtml = "Test123";
  }

  render() {
    return (
      <>
        <div className="App">
          <div ref={this.testRef} />
          <button onClick={this.changeText}> Draw circle inside div </button>
        </div>
      </>
    );
  }
}

它的工作方式可以在this codesandbox中看到:

现在,我尝试将d3圆添加到使用react-bootstrap创建的模态弹出窗口,如下所示:

import React from "react";
import ReactDOM from "react-dom";
import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import ButtonToolbar from "react-bootstrap/ButtonToolbar";
import * as d3 from "d3";

import "./styles.css";

class App extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = { modalShow: false };
  }

  testRef = React.createRef();

  showD3 = () => {
    this.setState({ modalShow: true });
    // console.log(this.testRef.current);
    let svg = d3
      .select(this.testRef.current)
      .append("svg")
      .attr("width", 200)
      .attr("height", 200);

    // Add the path using this helper function
    svg
      .append("circle")
      .attr("cx", 100)
      .attr("cy", 100)
      .attr("r", 50)
      .attr("stroke", "black")
      .attr("fill", "#69a3b2");
  };

  render() {
    let modalClose = () => this.setState({ modalShow: false });

    return (
      <>
        <ButtonToolbar>
          <Button variant="primary" onClick={this.showD3}>
            Launch vertically centered modal
          </Button>
        </ButtonToolbar>
        <Modal show={this.state.modalShow} onHide={modalClose}>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            D3 in React
            <div ref={this.testRef}></div>
          </Modal.Body>
        </Modal>
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

但是,这并不起作用,如codesandbox中所示:

它确实显示了模态对话框,但没有D3圆圈。为什么会这样?
参考文件:12

ccgok5k5

ccgok5k51#

我意识到我们必须在组件生命周期方法中处理呈现。在这个例子中是componentDidMount方法。我们必须在click事件中操作状态。我可以用类组件来做这件事,如下所示:

import React from "react";
import ReactDOM from "react-dom";
import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import ButtonToolbar from "react-bootstrap/ButtonToolbar";
import * as d3 from "d3";

import "./styles.css";

class App extends React.Component {
  constructor(...args) {
    super(...args);
    let _color = "#" + Math.floor(Math.random() * 16777215).toString(16);
    this.state = { modalShow: false, color: _color, showChart: false };
  }

  chart = React.createRef();

  componentDidUpdate() {
    if (this.state.modalShow) {
      this.renderChart();
    }
  }

  renderChart() {
    let svg = d3
      .select(this.chart.current)
      .append("svg")
      .attr("width", 200)
      .attr("height", 200);

    svg
      .append("circle")
      .attr("cx", 100)
      .attr("cy", 100)
      .attr("r", 50)
      .attr("stroke", "black")
      .attr("fill", this.state.color);
  }

  changeChartState() {
    let _color = "#" + Math.floor(Math.random() * 16777215).toString(16);
    this.setState({ color: _color });
  }

  showD3 = () => {
    this.setState({ modalShow: true });
    this.changeChartState();
  };

  render() {
    let modalClose = () => this.setState({ modalShow: false });

    return (
      <>
        <ButtonToolbar>
          <Button variant="primary" onClick={this.showD3}>
            Launch vertically centered modal
          </Button>
        </ButtonToolbar>
        <Modal show={this.state.modalShow} onHide={modalClose}>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            D3 in React
            <div ref={this.chart}></div>
          </Modal.Body>
        </Modal>
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Here is the working codesandbox

相关问题