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
There are basically two ways in which the data gets handled in React. It gets handled through state and props.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With