在ReactJS中更改视图

5

我并没有长时间使用ReactJS。我遇到了一个情况,我认为这一定很常见,但在任何示例中都没有看到它被解决,我想知道是否有任何最佳实践涉及其中。

场景非常简单,假设我的应用程序有三个表单:FormA、FormB和FormC。我将每个表单编写为单独的ReactJS组件。当用户访问网站时,会显示FormA。根据FormA上的输入,接下来将显示FormB或FormC,完全替换页面上的FormA。

我不认为“路由”是答案,因为我不希望URL反映当前应用程序状态,并且我不希望用户能够通过更改URL来更改表单。表单(组件)的切换应仅基于业务规则完成。

我知道ReactJS不是框架,但这似乎是一个足够常见的场景,已经围绕它发展出了一些有用的模式。只要指导方向就会非常有帮助。谢谢。

3个回答

6
解决方案是创建一个包含FormAFormBFormC的包装器Form组件,并根据其状态显示其中一个。例如:
const Form = React.createComponent({

  getInitialState() {
    return {
      form: 'formA'
      /* other state */
    }
  },

  render() {
    return (
      <div>
        {this.state.form === 'formA' ? <FormA onSubmit={this.saveFormData} /> : null}
        {this.state.form === 'formB' ? <FormB onSubmit={this.saveFormData} /> : null}
        {this.state.form === 'formC' ? <FormC onSubmit={this.saveFormData} /> : null}
      </div>
    )
  },

  saveFromData() {
    /* set state here */
  }

})

这种委托在React中很常见。通常,您应该在Form中管理表单逻辑,而FormAFormBFormC应该是哑组件,只能执行来自传递的props的函数。
请注意,上面的示例代码清单仅供演示。通常情况下,您不需要将form保留在状态中。相反,可以有例如usernamepasswordemail(或任何内容),并且您应该根据这些状态值检查要显示哪个表单。

谢谢你的回答和链接。这正是我在寻找的。 - ItsCosmo

2
这里有一个非常简单的解决方案,可以创建一个SwitchComponents组件:
// SwitchComponents.js:

import React from 'react';

export default function SwitchComponents({ active, children }) {
  // Switch all children and return the "active" one
  return children.filter(child => child.props.name == active)
}

并将其导入到您的应用程序中:

// App.js
import SwitchComponents from './components/SwitchComponents';

export default function App() {

const [activeComponent, setActiveComponent] = useState("questions")

return (
    <SwitchComponents active={activeComponent}>
      <Home name="home" />
      <Instructions name="instructions" />
      <FileboxContainer name="filebox" />
      <Questions name="questions" />
    </SwitchComponents>
  )
}

如果您不想传递“name”属性,您可以使用以下解决方案:

return children.filter(child => child.type.name == active)

但是这是您在定义组件时赋予您的函数名称,例如:
export default function MyFunctionName() { ... } // this is the name

即使您使用另一个名称导入它,您仍然必须使用该名称。

这对简化问题非常有帮助。 - Garrett Badeau

0
我认为你有一个主组件,它知道这三个表单组件。最初,它会呈现其中一个。当你对其中一个进行更改时,它会通过回调属性或Flux设计中的操作更改主组件的状态,并根据状态呈现不同的表单。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接