Using a variable inside a reactive rendering function

I study React and come across doubt, there are two codes in which the variables used by the render method in the component are declared in different places, I doubt why one works and the other doesn't.

import React from 'react';
import ReactDOM from 'reactDOM';

const myVar = 'hello';

class myComponent extends React.Component {
    render () {
       return <h1>{myVar}</h1>;
    }
}

ReactDOM(
    <myComponent />,
    document.getElementById('app')
);

This works, which means I can access the global variable in the rendering method.

But take this case that doesn't work

import React from 'react';
import ReactDOM from 'reactDOM';

class myComponent extends React.Component {
    const myVar = 'hello';

    render () {
       return <h1>{this.myVar}</h1>;
    }
}

ReactDOM(
    <myComponent />,
    document.getElementById('app')
);

I'm confused here, can someone explain this behavior

+4
source share
1 answer

inside a class that you don't define with variables. You just need to write myVar='hello'notconst myVar='hello'

The properties specified in the class definition are assigned the same attributes as in the object literal.

+9
source

Source: https://habr.com/ru/post/1691536/


All Articles