【问题标题】:How to display a new component on click of next button in React如何在 React 中单击下一个按钮时显示新组件
【发布时间】:2018-07-29 20:57:28
【问题描述】:

我有一个表单组件,我正在单击下一步按钮对该表单进行验证,一旦验证成功,我想呈现一个不同的组件。

在状态中,我将“showComponent”保持为假,单击该按钮时,我将其设为真。

_onButtonClick (event){
    event.preventDefault();
    this.setState({
        ...this.state,
        showComponent:  !this.state.showComponent
    })
    console.log("button clicked",this.state);
  }

按键逻辑:

<div>
    <button onClick={(event) => this._onButtonClick(event)}>Button</button>
         {this.state.showComponent ?<AddModules /> : null}
</div>

我能够渲染那个新页面,但它在同一页面上渲染,这是我不想要的。

【问题讨论】:

  • 我相信您在通过&lt;Route /&gt; 组件声明组件时可能没有使用exact 关键字。确保在声明路由时仅在路由与确切路径匹配时才加载组件,这样声明它:
  • 谢谢,我已经这样做了,但是路径问题存在,谢谢您的指导。

标签: reactjs react-native react-router


【解决方案1】:

我认为react-router-dom 为您提供的&lt;Route /&gt; 组件正是您所需要的。

看看example in the react-router docs。注意他们如何设置&lt;Route /&gt;。他们还有一个example in the docs,关于如何防止某人进入另一个页面。

我还快速创建了一个demo in CodeSandbox,它与您正在寻找的内容更相似。

【讨论】:

  • 谢谢安东尼,我已经做到了,但路径问题存在,谢谢你的指导,特别是演示的谢谢,你能告诉我如何将对象从第一个组件传递到其他组件吗?反之亦然。这样我就可以将两个对象存储在父对象中并保存在数据库中。
  • 您应该能够在&lt;Route /&gt; (see docs here) 中使用renderchildren 属性。这允许您像往常一样在 JSX 中进行渲染,而不仅仅是传递一个组件。看看这个CodeSandbox demo,它显示了不同路由中的两个组件共享相同的数据。
  • 点击后退按钮时,是否可以显示用户之前在上一页输入的内容? “价值 2”?
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 2014-11-28
  • 2018-05-04
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多