Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to use private variables and methods in React.js

I've noticed that I could use private variables like this:

var Hello = React.createClass(new (function(){

    var name;

    this.getInitialState = function() {
        name = "Sir " + this.props.name;
        return null;
    };

    this.render = function() {
        return <div>Hello {name}</div>;
    };
})());

React.render(<Hello name="World" />, document.getElementById('container'));

Why I should not be doing this?

Thank you for any help

like image 612
melanke Avatar asked Sep 10 '15 02:09

melanke


People also ask

What are the two way to handle data in React?

There are basically two ways in which the data gets handled in React. It gets handled through state and props.

Can I use VAR in React?

If you use var outside of a function, it belongs to the global scope. If you use var inside of a function, it belongs to that function. If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block. var has a function scope, not a block scope.

Which method from React did we use to create a state variable?

Line 1: We import the useState Hook from React. It lets us keep local state in a function component. Line 4: Inside the Example component, we declare a new state variable by calling the useState Hook. It returns a pair of values, to which we give names.


1 Answers

If you are using es7, you can define class properties as a private variables like this:

class Hello extends React.Component {
  name = 'Jack';
  render() {
    return (
      <div>
        {this.name}
      </div>
    );
  }
}
export default Hello;

Be sure to use babel to compile your code with stage 0

like image 72
xcatliu Avatar answered Sep 19 '22 19:09

xcatliu