如何在反应中单击按钮将一个组件移动到另一个组件?

2024-04-11

您能告诉我如何在反应中单击按钮时将一个组件移动到另一个组件吗? 我得到了react-router.js来自 cdn 。我不知道如何使用这个 js ..我想展示second component on button click of第一个组件`这是我的代码

http://codepen.io/anon/pen/jVoZjW?editors=1010 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')); 

有很多方法可以实现这一点,所有这些方法都有用。这只是众多方法之一:

我在 codepen 上留下了这个答案的替代方案:http://codepen.io/dirtyredz/pen/gLJeWY 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')); 

这是一个简单的例子,就像我之前所说的那样,其他人可能会更好,但这按预期工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在反应中单击按钮将一个组件移动到另一个组件? 的相关文章

随机推荐