不变违规:预期onClick
侦听器是一个函数,而是获得了string
类型的值。 (/node_modules/fbjs/lib/invariant.js:42)
import React from "react"
class App extends React.Component{
constructor(){
super()
this.state = {
isLoggedIn : false,
innerText : "Log In"
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState(prevState => {
if(prevState.isLoggedIn === true){
return{
isLoggedIn: false,
innerText: "Log in"
}
return{
isLoggedIn : true,
innerText: "Log out"
}
}
})
}
render(){
return(
<div>
<h1>You are not logged</h1>
<button onClick = "handleClick()">{this.state.innerText}</button>
</div>
)
}
}
export default App
答案 0 :(得分:1)
将事件侦听器添加到按钮的正确语法如下:
<button onClick={this.handleClick}>{this.state.innerText}</button>
您还可以清理“ handleClick”功能,使其更加内联。全部放在一起看起来像这样:
class App extends React.Component{
constructor(){
super()
this.state = {
isLoggedIn : false,
buttonTitle : "Log In"
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState(prevState => ({
isLoggedIn: !prevState.isLoggedIn,
buttonTitle: `Log ${prevState.isLoggedIn ? 'in' : 'out'}`
})
}
render(){
return(
<div>
<h1>You are not logged</h1>
<button onClick={this.handleClick}>{this.state.buttonTitle}</button>
</div>
)
}
}
export default App