简体   繁体   English

Reactjs 类到功能组件问题

[英]Reactjs Class to Functional component problem

I am having hard time trying to convert class component to functional component.我很难尝试将类组件转换为功能组件。 Requesting your help in this please.请在这方面寻求您的帮助。

Class code:班级代码:

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

I have tried to do it this way, but imported function drawOnCanvas is not getting called, also this.node am not sure how to set it.我试过这样做,但是导入的函数 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}           
    />;    
}

there are four things here这里有四件事

  • one you where trying to assign a parameter to a constant in the save node function您尝试将参数分配给保存节点功能中的常量的地方

  • two you cannot use 'this' keyword in functions only in classes二你不能只在类中的函数中使用'this'关键字

  • three why is the ref variable even there in the first place三为什么 ref 变量甚至首先存在

  • four u are using drawOnCanvas twice one from the import and one from the function which is an error四个你正在使用 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