首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不变冲突:对象作为React子对象无效(找到:[对象HTMLCanvasElement])

不变冲突:对象作为React子对象无效(找到:[对象HTMLCanvasElement])
EN

Stack Overflow用户
提问于 2018-08-09 12:43:56
回答 1查看 844关注 0票数 2

全错误日志:

不变冲突:对象作为React子对象无效(找到:对象HTMLCanvasElement)。如果您打算呈现一个子集合,请使用数组代替。在CanvasEngine中 以上错误发生在组件中:在CanvasEngine中

渲染没有返回。elementCanvas有什么问题: HTMLCanvasElement ?!

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

代码语言:javascript
复制
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")
);
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-09 13:24:20

请您不要使用document.createElement(),您可以尝试使用React.createElement()吗?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51767405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档