簡體   English   中英

Reactjs 類到功能組件問題

[英]Reactjs Class to Functional component problem

我很難嘗試將類組件轉換為功能組件。 請在這方面尋求您的幫助。

班級代碼:

import React, { Component } from "react";

import GenericChartComponent from "../GenericChartComponent";
import { drawOnCanvas } from "./EdgeCoordinate";

export default class PriceCoordinate extends Component{
    constructor(props) {
        super(props);
        this.saveNode = this.saveNode.bind(this);
        this.drawOnCanvas = this.drawOnCanvas.bind(this);
    }

    saveNode(node) {
        this.node = node;
    }

    drawOnCanvas(ctx) {     
        drawOnCanvas(ctx, props);
    }

    render() {
        const ref = { ref: this.saveNode } ;

        return <GenericChartComponent           
            canvasDraw={this.drawOnCanvas}           
        />;
    }
}

我試過這樣做,但是導入的函數 drawOnCanvas 沒有被調用,this.node 也不知道如何設置它。

import React, { Component } from "react";

import GenericChartComponent from "../GenericChartComponent";
import { drawOnCanvas } from "./EdgeCoordinate";

function PriceCoordinate(props){
    const node = null; 

    const saveNode= (node) =>{
        this.node = node;
    }

    const drawOnCanvas = (ctx) => {     
        drawOnCanvas(ctx, props);
    }
     
    const ref = { ref: this.saveNode } ;

    return <GenericChartComponent           
        canvasDraw={this.drawOnCanvas}           
    />;    
}

這里有四件事

  • 您嘗試將參數分配給保存節點功能中的常量的地方

  • 二你不能只在類中的函數中使用'this'關鍵字

  • 三為什么 ref 變量甚至首先存在

  • 四個你正在使用 drawOnCanvas 兩次,一次來自導入,一次來自函數,這是一個錯誤

import React, { Component } from "react";

import GenericChartComponent from "../GenericChartComponent";
import { drawOnCanvas } from "./EdgeCoordinate";

function PriceCoordinate(props){
    let node; 

    const saveNode= (node2) =>{
        node = node2;
    }

    const draw = (ctx) => {     
        drawOnCanvas(ctx, props);
    }
     
    const ref = { ref: saveNode } ;

    return <GenericChartComponent           
        canvasDraw={draw}           
    />;    
}

暫無
暫無

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

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