【发布时间】: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