Мне нужно нарисовать прямоугольник, используя холст. Холст должен быть в дочернем компоненте. Как и функция updateCanvas. Возможно ли это сделать?
Я попытался нарисовать прямоугольник в родительском компоненте, и все работает нормально, но в этом случае мне нужно, чтобы холст был в дочернем компоненте.
// 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>
);
}
}
Ожидаемый результат. Нарисованный прямоугольник.