简体   繁体   中英

Change text of button when pressing it ReactJS

I want to change the text of a button when I press it.

This is what I want to achieve: https://codepen.io/gaearon/pen/xEmzGg?editors=0010 , but I can't get my code to work (newbie).

class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState(prevState => ({
      open: prevState.open
    }))
  }

  renderInner() {
      if (!this.props.value) return <td className = "inactive" > < /td>
      if (!this.state.open && this.props.schema.type === 'belongs_to')
      return <td onClick={(e) => this.setState({open: !this.state.open})}>
        <button onClick={this.handleCLick}>
          {this.state.open ? 'OFF' : 'ON'}
        </button>
      </td>
}

Here's my code and as you might have seen I want to toggle the text OFF and ON when pressing the button. I can add more code if needed. Really grateful for all the support I can get.

The bug is in handler:

this.setState(prevState => ({
  open: !prevState.open
}))

You are setting it to the same value, as it was before.. with !bool you can switch the value

Additionally the condition is not making any sense:

  if (!this.state.open && this.props.schema.type === 'belongs_to')
  return <td onClick={(e) => this.setState({open: !this.state.open})}>
    <button onClick={this.handleCLick}>
      {this.state.open ? 'OFF' : 'ON'}
    </button>
  </td>

This means only if the condition is met, you component will return something..

true === (!this.state.open && this.props.schema.type === 'belongs_to')

Here is what you are looking for:

handleClick() {
    const open = !this.state.open;
    this.setState({open})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM