how to move one component to another component on button click in react?

徘徊边缘 提交于 2019-12-06 17:00:29

There is many ways this can be accomplished, all of which have there place. This is but one of many methods:

I left an alternitive to this answer aswell this answer on the codepen: http://codepen.io/dirtyredz/pen/gLJeWY

class Abc extends React.Component {
  constructor(){
    super();
    this.state={first: true};
  }
  handle(){
    alert('move to second component')
    this.setState({first: false})
  }
  render (){
    return (
      <div>
        <button onClick={this.handle.bind(this)}>move to second page</button>
        {this.state.first == true && <Pqr/>}
        {this.state.first == false && <Sqr/>}
      </div>
    );
  }
}

class Pqr extends React.Component {
  render (){
    return (<div><h1>First</h1></div>)
  }
}
class Sqr extends React.Component {
  render (){
    return <h1>Second</h1>
  }
}
ReactDOM.render(<Abc/>,document.getElementById('root')); 

This is a quick example, like i said earlier others may be better but this works as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!