我无法使用 canvas 作为子组件绘制矩形

I can not draw a rectangle using canvas as a child component

我需要使用 canvas 绘制一个矩形。 Canvas 必须在子组件中。就像 updateCanvas 函数一样。可以这样做吗?

我试图在父组件中绘制一个矩形并且一切正常,但在这种情况下我需要 canvas 在子组件中。

// Parent Component

import React, { Component } from "react";
import PropTypes from "prop-types";
import Shape from "../../components/Shape";
import "./groupShapes.css";
export default class GroupShapes extends Component {
  constructor(props) {
    super(props);
    // this.state = {
    //   reactanglesOptions: [0, 1, 2]
    // };
    this.canvas = React.createRef();
  }
  componentDidMount() {
    this.updateCanvas();
  }

  updateCanvas = () => {
    const ctx = this.canvas.getContext("2d");
    ctx.fillRect(0, 0, 100, 100);
  };

  render() {
    // const { reactanglesOptions } = this.state;
    return (
      <div className="groupContainer">
        <Shape ref={this.canvas} />
      </div>
    );
  }

  static propTypes = {
    prop: PropTypes
  };
}

// Child Component
import React, { Component } from "react";

export default class Shape extends Component {
  render() {
    const { ref } = this.props;
    return (
      <div>
        <canvas ref={ref} width={300} height={300} />
      </div>
    );
  }
}

预期结果。绘制的矩形。

在 React 文档中它说如果你通过它使用 ref.current

<canvas ref={ref.current} width={300} height={300} />

我认为您想要的是 <Canvas /> 位于子组件中并更新父组件中的功能。 工作 stackblitz code

// index.js
import React, { Component } from 'react';
import PropTypes from "prop-types";
import { render } from 'react-dom';
import Shape from './Shape';

class App extends Component {
  updateCanvas = (ctx) => {
    ctx.fillRect(0, 0, 100, 100);
  };

  render() {
    return (
      <div>
        <Shape updateCanvas={this.updateCanvas} />
      </div>
    );
  }
    static propTypes = {
    prop: PropTypes
  };
}

render(<App />, document.getElementById('root'));

Shape.js

import React from 'react';

export default class Shape extends React.Component {
  componentDidMount() {
    const canvas = this.refs.canvas
    const ctx = canvas.getContext("2d")
    this.props.updateCanvas(ctx)
  }
  render() {
    return (
      <div>
        <canvas ref='canvas' width={300} height={300} />
      </div>
    );
  }
}

希望对您有所帮助!!!