React:混合受控组件和非受控组件在一个多步表单中的最佳实践。

huangapple go评论73阅读模式
英文:

React: best practices of mixing controlled components and uncontrolled components in one multi-step form

问题

使用React中的“受控组件”模式来创建复杂表单是简单而直接的。

然而,当表单中有一个字段是“非受控组件”时,情况可能会变得相当复杂(例如,一个使用jQuery构建的非常复杂的遗留系统组件)。

非受控组件不了解“value”和“onChange”,它的唯一API是“setData”和“getData”。

更糟糕的是,这个组件可能放在多步表单的第二步,或者只在选择某个选项时才显示。也就是说,这个组件可能会以难以预测的方式挂载和卸载,其“ref”通常不可用。

如何处理这个问题的一些良好实践是什么?我们如何编写可预测、优雅和可维护的代码,同时集成受控组件和非受控组件?

英文:

Using the pattern of controlled components in react to make a complex form is easy and straight-forward.

However, things can become quite tricky when we have one field in the form that is an uncontrolled component. (e.g. a very complex legacy system component that was built with jQuery)

The uncontrolled component does not know about value and onChange, and its only API is setData and getData.

What's worse, this component may be placed on the second step of a multi-step form, or it may only show when a certain option is selected. That is to say, this component can mount and unmount quite unpredictably, its ref often not available.

What are some of the good practices to deal with this problem? How can we write predictable, elegant and maintainable code that integrates both controlled components and uncontrolled components?

答案1

得分: 2

一种我可以想到的方法是使用高阶组件(HOC)来包装这个不受控制的组件。高阶组件可以从 props.value 读取数据,在 componentDidMount 中调用 setData,并在 componentWillUnmount 中调用 getDataprops.onChange

英文:

One way that I can think of is to wrap the uncontrolled component with an HOC, which reads data from props.value and calls setData in componentDidMount, and calls getData and props.onChange in componentWillUnmount.

huangapple
  • 本文由 发表于 2020年1月3日 23:39:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定