gpt4 book ai didi

javascript - onclick监听器-字符串类型的值

转载 作者:行者123 更新时间:2023-11-29 22:56:59 25 4
gpt4 key购买 nike

不变违规:预期 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

最佳答案

向按钮添加事件监听器的正确语法如下:

<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

关于javascript - onclick监听器-字符串类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56483616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com