【问题标题】:Accessing functional component's methods from the 'outside'从“外部”访问功能组件的方法
【发布时间】:2020-10-28 17:46:59
【问题描述】:

假设我想通过从应用程序外部调用方法来控制我的应用程序的加载状态,如下所示:

setLoading(true)

我已经实现了一个类似的功能组件:

import React from 'react';

function App() {
  const [loading, setLoading] = React.useState(true);
  window.setLoading = (isLoading) => { setLoading(isLoading) };

  if (loading) return 'Loading...';

  return 'App content';
}

但我相信将setLoading() 映射到window 并不是最好的方法。那么是否有可能以不同的方式来做呢?

如果我有一个类组件,它会是这样的:

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
    }
  }

  setLoading = (loading) => {
    this.setState({ loading });
  }

  render() {
    return(this.state.loading ? 'Loading...' : 'App content');
  }
}

然后在渲染时,我将使用回调 ref 使整个组件及其所有方法都可用。

<App ref={(app) => { window.app = app }} />
app.setLoading(true)

这种方法也会污染全局范围,但更简洁 - 组件作为一个整体公开。

由于这两种方法都不是最优的,我应该使用哪一种?有没有更好的?

【问题讨论】:

  • “应用程序之外”是什么意思?你想从另一个组件中使用它,还是完全在 React 组件之外使用它?
  • @Eldrax 完全在 React 之外 - 例如通过在浏览器的控制台中运行 setLoading(true)。查看我实现该组件的codesandbox.io/s/crimson-rgb-tcmjw。如果在新选项卡中打开应用并运行命令,内容会发生变化。

标签: reactjs react-functional-component react-class-based-component


【解决方案1】:

与公开整个组件相比,我认为只向外部公开所需的功能更简洁。如果您无论如何都暴露在外部,那么将 React 组件暴露在 React 上下文之外没有多大意义 - 相反,window.setAppLoading 之类的东西似乎更像是一个用于控制应用程序状态的外部函数,这可能就是您需要。

基本上,如果您想向外部公开某个控制您应用的某些功能的函数,那么只公开它而不是公开应用内部的一部分会更干净。

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2015-04-21
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多