我正在尝试实现一个特定的 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>
现在考虑我们不能/不应该从父组件调用子组件的方法的 react 方式。在这里,我想在每个组件中保留一个 isValid
方法,该方法将在单击 Next/Finish
按钮时从父 Wizard
组件调用。 React 方式建议将状态和逻辑移动到父组件。但那样我将无法重用相同的组件,例如ComponentA
在任何其他向导或任何其他地方,否则我将不得不在每个使用 ComponentA
的父组件中复制验证逻辑。使用 ref
或 this approach我可以轻松访问子组件的方法 (isValid
)。
截至今天(React 版本 16.6),我没有看到在 React 中根据需要使用此模式的任何陷阱。在 react 中使用这种模式可能会遇到什么问题?在这个特定示例中是否有更好的选项,我可以使用它在步骤组件(例如 ComponentA
)中保留 isValid
方法以供重用?
最佳答案
简答
是的。
长答案
来自 React's doc on refs :
In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props.
Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy.
创建引用是为了在特定用例(焦点、文本选择、媒体播放、第三方库等)中访问 DOM,但在尝试让其他组件执行操作时应避免使用它们。
当然你可以有一个 React 应用程序,它可以在使用 refs 调用子组件方法的同时工作,但是,是的,这是非常反模式的。
关于javascript - 在 react 中从父组件调用子组件的方法是否反模式,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54159422/