如何在按钮点击时将一个组件移动到另一个组件? [英] how to move one component to another component on button click in react?

查看:207
本文介绍了如何在按钮点击时将一个组件移动到另一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何在点击按钮时将一个组件移动到另一个组件吗?
我从cdn得到 react-router.js 。我不知道如何使用这个js ..我想显示第二个组件按钮点击第一个组件`这里是我的代码

could you please tell me how to move one component to another component on button click in react ? I get the react-router.js from cdn .I don't know how to use this js ..I want to show second component on button click offirst component` here is my code

http://codepen.io/anon/pen/jVoZjW?editors=1010

class Abc extends React.Component {
  handle(){
    alert('move to second component')
  }
   render (){
     return (<div><h1>second</h1><button onClick={this.handle}>move to second page</button></div>);

   }
}
class Pqr extends React.Component {
   render (){
     return (<div><h1>second</h1><button>click</button></div>)

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


推荐答案

有很多方法可以实现,所有这些那里有。这只是众多方法中的一种:

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

我在这个答案中留下了这个答案的替代品:
http://codepen.io/dirtyredz/pen/gLJeWY

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.

这篇关于如何在按钮点击时将一个组件移动到另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆