javascript - 在 react 中从父组件调用子组件的方法是否反模式,为什么?

标签 javascript reactjs reactive-programming

我正在尝试实现一个特定的 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 的父组件中复制验证逻辑。使用 refthis 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/

相关文章:

angular - 无法将 'Rx' 导入我的 Angular 2 应用程序

android - RxJava : Executing an AsyncTask from Subscribe() fails

javascript - html youtube 自定义播放按钮

javascript - 使用 Javascript 查找上一个和下一个 li

javascript - 使用 JSON 响应的数据表

ruby - 如何在 Hyperstack 中导入 Material 图标?

javascript - React 列表的无限滚动

javascript - 是否可以显示所选周的行数?

reactjs - 还是要使用npm start从带有前缀的网址(例如/client/static)中转换/static?

java - 如何将 Observable.fromIterable 中的项目索引传递给 subscribe 方法中的 onNext ?