不变违规:对象作为React子对象无效(发现:[object HTMLCanvasElement])

时间:2018-08-09 12:43:56

标签: reactjs

完整错误日志:

  

不变违规:对象作为React子对象无效(发现:   [object HTMLCanvasElement])。如果您打算呈现一个   孩子,请改用数组。       在CanvasEngine中

     

上述错误发生在组件中:       在CanvasEngine中

render没有回报。 elementCanvas出了点问题:HTMLCanvasElement?!

我想从代码中获取html元素,我尝试将其存储在this.state中,但仍无法正常工作...

access_token
import * as React from "react";

export class CanvasEngine extends React.Component<{name:string}, {}, void > {

    private elementCanvas: HTMLCanvasElement;
    private programName: string = " test ";
    private width: number = 100;
    private height: number = 100;

    private test: number = 1;

    constructor(props: {name:string}) {
        super(props);

        this.state = {  elementCanvas : document.createElement('canvas') };
        //super( {name} );
        this.elementCanvas = document.createElement('canvas');
        this.elementCanvas.width = 200;
        this.elementCanvas.height = 200;
        //document.body.appendChild(this.elementCanvas);
        console.log("constructor");
        this.tick();
       
    }

    componentDidMount() {
        console.log("!componentDidMount!");
     }

    tick() {

        let context = this.elementCanvas.getContext("2d");
        context.fillStyle = "lime";
        context.clearRect(0, 0, this.width, this.height);

        context.save();
        context.translate(100, 100);

        this.test += 0.01;
        context.rotate(this.test);
        context.fillStyle = "#F00";
        context.fillRect(50, 50, 100, 100);
        context.restore();

        setTimeout( () => { this.tick() } , 30 );
      }

    public render() {
        return <> {this.elementCanvas} </>;
    }
}
//
import * as React from "react";
import * as ReactDOM from "react-dom";

import { ProjectName } from "./components/project-name";
import { CanvasEngine } from "./components/canvas";

ReactDOM.render(
    <>
    <h1>Page title</h1>,
    <CanvasEngine name="nidza" />,
    <ProjectName compiler="TypeScript" framework="React" />
    </>,
    document.getElementById("root")
);

1 个答案:

答案 0 :(得分:1)

您可以代替document.createElement()尝试使用React.createElement()