Part of the component lifecycle, similar to created/mounted.
Part of the component lifecycle, similar to destroyed
There is not explicit field that holds the internal state. Instead, we have to rely on the state
property (set during the class constructor
function).
State can't be modified directly, modifications need to go through setState
. This function accepts
both a plain object or a function with prevState
and props
as arguments.
this.setState((prevState) => ({
items: prevState.items.concat(newItem),
text: ''
}))
Props are passed from parent to son exactly like in Vue. If the component is functional, props will
be passed as an argument of the function. If it's not, we can access it via this.props
.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>
}
To allow React components to be defined as classes (hence having an internal state, among others), we
have to use ES6 Classes. One important thing is that we always need to call super(props)
in the class
constructor. This will call the parent constructor with the new props.
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {name: 'Hector'}
}
render() {
return <h1>Hello (this.state.name}</h1>
}
}
Unlike Vue, where "custom" functions go under the 'methods' property, these can be written "anywhere" in the component declaration in React.
class MyComponent extend React.Component {
constructor (props) {
super(props)
}
componentDidMount () {
this.saySomething()
}
saySomething () {
console.log('Something')
}
}
Events are bound as in plain JS:
<button onclick="activateLasers()">
Activate Lasers
</button>
But camelcasing the event name:
<button onClick={activateLasers}>
Activate Lasers
</button>
There's something weird we have to do when we define an event handler:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
// ...
}
}
So in the class constructor we need to re-assign the function definition so we can use
this
on the function.