簡體   English   中英

React:為什么這個 React 組件不渲染?

[英]React: Why won't this React Component render?

我正在使用 Electron 和 Meteor.js 在 React 中編寫桌面應用程序

我有以下反應組件 class:

import React from "react"

export class MemoryMap extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            memory : [],
            mem_max : 0xFFFF,
        }

        this.readByte = function(byte){
            return this.state.memory[byte];
        };

        this.writeByte = function(mem_addr, byte){
            if(mem_addr >= 0 && mem_addr < this.state.mem_max) {
                this.state.memory[mem_addr] = byte;
            }
        };

        for(let i = 0; i < 10000; i++){
            this.state.memory[i] = 0x0000;
        }



    }

    render(){
        return(
            <div>
                <h1>{this.state.memory[0x0000]}</h1>
            </div>
        );
    }
}

export const MemMap = new MemoryMap();

我嘗試在 Main.jsx 中呈現這個 class :

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import {MemMap} from "./CPU_Elements/MemoryMap";


Meteor.startup(() => {

  render(<MemMap/>, document.getElementById("react-target"));
  Desktop.send("desktop", "init");
});

當以這種方式調用時,程序會在這一行崩潰。 Desktop.send function 永遠不會被調用。

如果我這樣重寫 MemoryMap,則渲染 function 變為 class 方法:

import React from "react"

export class MemoryMap extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            memory : [],
            mem_max : 0xFFFF,
        }

        this.readByte = function(byte){
            return this.state.memory[byte];
        };

        this.writeByte = function(mem_addr, byte){
            if(mem_addr >= 0 && mem_addr < this.state.mem_max) {
                this.state.memory[mem_addr] = byte;
            }
        };

        for(let i = 0; i < 10000; i++){
            this.state.memory[i] = 0x0000;
        }

        this.render = function(){
            return(
                <div>
                    <h1>{this.state.memory[0x0000]}</h1>
                </div>
            );
        }

    }


}

export const MemMap = new MemoryMap();

並且 main.jsx 文件被重寫以調用該方法:

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import {MemMap} from "./CPU_Elements/MemoryMap";


Meteor.startup(() => {

  render(MemMap.render(), document.getElementById("react-target"));
  Desktop.send("desktop", "init");
});

元素渲染得很好。

為什么是這樣? 為什么我不能使用 HTML 標簽格式,如 React 的教程中所示?

改變這個:

export const MemMap = new MemoryMap();

至:

export const MemMap = MemoryMap;

由於您應該導出組件定義,而不是創建它的實例並導出它。 (這就是為什么obj.render()有效但<obj/>無效的原因。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM