Onclick侦听器-字符串类型的值

时间:2019-06-06 19:02:59

标签: javascript reactjs jsx

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

1 个答案:

答案 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