Deb*_*der 6 javascript reactive-programming reactjs
我正在尝试实现一个Wizard用户可以使用以下模式使用的特定组件。
<Wizard {...wizardProps} onFinish={this.handleFinish}>
<WizardStep onValidate={() => this.componentARef.isValid()}>
<ComponentA onRef = { ref => (this.componentARef = ref)}/>
</WizardStep>
<WizardStep onValidate={() => this.componentBRef.isValid()}>
<ComponentB onRef = { ref => (this.componentBRef = ref)}/>
</WizardStep>
<WizardStep onValidate={() => this.componentCRef.isValid()}>
<ComponentC onRef = { ref => (this.componentCRef = ref)}/>
</WizardStep>
</Wizard>
Run Code Online (Sandbox Code Playgroud)
现在考虑反应方式,我们不能/不应该从父组件调用子组件的方法。在这里,我想在每个组件中保留一个方法,单击按钮时isValid将从父组件中调用该方法。React 方式建议将状态和逻辑移动到父组件。但这样我将无法在任何其他向导或任何其他地方重用相同的组件,或者我将不得不在每个正在使用. 使用或这种方法我可以轻松访问子组件的方法()。WizardNext/FinishComponentAComponentArefisValid
截至今天(React 版本 16.6),我没有看到在 React 中根据需要使用此模式有任何陷阱。在反应中使用这种模式可能会遇到什么问题?在这个特定的示例中是否有更好的选择,使用它我可以将isValid方法保留在步骤组件(例如ComponentA)中以供重用?
是的。
\n\n\n\n\n在典型的 React 数据流中,props 是父组件与其子组件交互的唯一方式。要修改子项,您可以使用新的道具重新渲染它。
\n\n您的第一个倾向可能是在您的应用程序中使用 \xe2\x80\x9c 的引用来使事情发生 \xe2\x80\x9d 。如果是这种情况,请花点时间更仔细地思考状态应该在组件层次结构中的哪个位置拥有。
\n
创建 Ref 是为了在特定用例(焦点、文本选择、媒体播放、第三方库等)中访问 DOM,但在尝试使其他组件执行操作时应避免使用它们。
\n\n因此,你当然可以拥有一个在使用 refs 调用子组件方法时工作的 React 应用程序,但是,是的,这是非常反模式的。
\n| 归档时间: |
|
| 查看次数: |
1464 次 |
| 最近记录: |