Reputation: 65
import React, { Component } from 'react'
class Columns extends Component{ constructor(props){ super(props)
this.state={
message:'Hello'
}
}
changeMessage(){
this.setState=({
message:'Welcome'
})
}
render(){
return(
<div>
<div>{this.state.message}</div>
<button onClick={this.changeMessage}>Click</button>
</div>
)
}
} export default Columns
Upvotes: 2
Views: 155
Reputation: 27285
Because passing it as this.changeMessage
detaches it from the component scope. When the button invokes it, "this" is no longer the component.
Change it to an arrow function: () => this.changeMessage()
I've tried to explain this scope issue in another answer in the past if you want the details.
Also, as Aaron points out you also have an extraneous =
in your changeMessage handler.
Upvotes: 3
Reputation: 2237
As ray hatfield said above, you're losing the this
context and need to use an arrow function, but also you're not calling setState
; you're overriding it.
Remove the =
from
this.setState=({
message:'Welcome'
})
so that it says:
this.setState({
message:'Welcome'
})
Upvotes: 5