最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - use of variable inside render function of react component - Stack Overflow

programmeradmin0浏览0评论

I am learning React and came across a doubt, there are two codes in which variables used by render method in ponent are declared at different places, my doubt is why one works and 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, means I am able to access global variable in render method.

But take this case which does not 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 am confused here, can somebody explain this behavior

I am learning React and came across a doubt, there are two codes in which variables used by render method in ponent are declared at different places, my doubt is why one works and 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, means I am able to access global variable in render method.

But take this case which does not 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 am confused here, can somebody explain this behavior

Share Improve this question asked Dec 30, 2017 at 9:16 madhurmadhur 1,0011 gold badge15 silver badges23 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

inside the class you don't define variables. You just have to write myVar='hello' not const myVar='hello'

Properties specified in a class definition are assigned the same attributes as if they appeared in an object literal.

发布评论

评论列表(0)

  1. 暂无评论