I want to use ES6 (ES2015) as much as possible for my small project. Now I want to use arrow functions with React.
// What I want
let Text = React.createClass({
componentDidMount: () => {
setInterval(this.updateCurrentTime, 1000);
}
}
// What I have
let Paragraph = React.createClass({
render: () => (<div className="MySuperTable"><Text name="Dodo" startDate={(new Date()).toString()} /></div>)
});
let Text = React.createClass({
getInitialState: function () {
return {
currentTime: (new Date()).toString()
}
},
componentDidMount: function () {
setInterval(this.updateCurrentTime, 1000);
},
updateCurrentTime: function () {
this.setState({
currentTime: (new Date()).toString()
});
},
render: function () {
return (
<div>
<span>Hello my name is {this.props.name}</span>
<span>And I was born on {this.props.startDate}</span>
<span>And I now it's {this.state.currentTime}</span>
</div>
);
}
});
ReactDOM.render(
<Paragraph/>,
document.getElementById('container')
);
this
will be the object passed into createClass
itself, is this correct? Text
instance?Thanks in advance.
Learn more at the React docs. If you use arrow functions within render , each call to render will create new function objects. If you then pass these functions to child elements via props , optimizations based on PureComponent or shouldComponentUpdate will fail (as the arrow function props will change on every render).
Passing an arrow function in render will cause React to create a new function each time the component renders. But you don't need to worry because the impact on performance is very minuscule. It's very unlikely that your users will experience a noticeable lag just because of arrow functions in render.
In short, with arrow functions there is no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions, the this keyword always represents the object that defined the arrow function.
Define the function in the parent component. Pass it as a prop to the child component, e.g. <Child handleClick={handleClick} /> . Use the function in the child component.
You can change your code with ES2015
like this
class Text extends React.Component {
constructor() {
super();
this.state = { currentTime: (new Date()).toString() };
}
componentDidMount() {
setInterval(() => this.updateCurrentTime(), 1000);
}
updateCurrentTime() {
this.setState({
currentTime: (new Date()).toString()
});
}
render() {
return <div>
<span>Hello my name is { this.props.name }</span>
<span>And i was born { this.props.startDate }</span>
<span>And i now it's { this.state.currentTime }</span>
</div>
}
};
let Paragraph = () => {
return <div className="MySuperTable">
<Text name="Dodo" startDate={ (new Date()).toString() } />
</div>
};
Example
React - Reusable Components
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