Я не могу нарисовать прямоугольник, используя холст как дочерний компонент - PullRequest
0 голосов
/ 05 июня 2019

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

Ожидаемый результат. Нарисованный прямоугольник.

Ответы [ 2 ]

0 голосов
/ 06 июня 2019

Я думаю, что вы хотите, чтобы <Canvas /> был в дочернем компоненте и обновлял функциональность в родительском компоненте.Рабочий код стекаблиц

// 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>
    );
  }
}

Надеюсь, что поможет !!!

0 голосов
/ 06 июня 2019

В реагирующих документах говорится, что если вы передаете его, используйте ref.current

<canvas ref={ref.current} width={300} height={300} />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...