简体   繁体   中英

How to replace one React Component with another OnClick?

I have a "sign up" button. When it is clicked, I would like for it to render a new component, called "SignUp". I would like for the new component to replace the "sign up" button.

Currently, I am using setState so that when the button is clicked, a new component is rendered. However, the button is not being replaced, the "SignUp" component is just rendered beside the button. What may be a good approach for me to replace the button with the new component being rendered?

I have provided my code below:

  export default class SignUpSignIn extends Component {

  constructor() {
     super();

     this.state = {
       clicked: false
     };

     this.handleClick = this.handleClick.bind(this);
   }

  handleClick() {
    this.setState({
      clicked: true
    });
  }

  render () {

    return (
    <div id="SignUpSignInDiv">

      <Col md="12" sm="12" xs="12" className="text-center">

        <div onClick={this.handleClick}>

          {this.state.clicked ? <SignUp /> : null}

        <Button id="SignUpButton" color="primary"> Sign Up </Button>

        </div>

       </Col>

    </div>
  )

  }
}

Well, you're not rendering both components conditionally, only the SignUp . Instead of having null in your ternary, render the sign in button when state.clicked === false :

render () {
  return (
    <div id="SignUpSignInDiv">
      <Col md="12" sm="12" xs="12" className="text-center">
        {this.state.clicked ? (
          <SignUp />
        ) : (
          <Button id="SignUpButton" color="primary" onClick={this.handleClick}> Sign Up </Button>
        )}
       </Col>
    </div>
  )
}

one way to do it is like this , i didnt test it yet but it should work

render () {
let show = <div></div>
if(this.state.clicked){
show = <SignUp />
}
  return (
    <div id="SignUpSignInDiv">
      <Col md="12" sm="12" xs="12" className="text-center">
          {show}
          <Button id="SignUpButton" color="primary" onClick={this.handleClick}> Sign Up </Button>

       </Col>
    </div>
  )
}

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