create-react-app:如何在 React 渲染之前加载 html

create-react-app: how to load html before React renders

我正在尝试在 React 加载之前添加启动画面。

因为我使用的是 React 脚本/react-app,所以我的 index.tsx 只有这一部分:

ReactDOM.render(<App />, document.getElementById("root"));

我尝试在同一页面上添加我自己的 div,但它没有显示。

我想在响应加载到 avoid/hide 渲染元素的移动之前,在 1 秒计时器上显示一个简单的空白屏幕和我的初始图像。

** 如果我确实在 app.tsx 中添加了屏幕,则移动发生在屏幕加载之前

更新

正如 Rishabh 在下面指出的那样,index.html 在 /public 文件夹中。所以我最终结合了两种方法。

  1. 在反应开始之前添加一个屏幕:

    <div id="root">
      <div id="dimScreen">
        <img src="/img/logo.png" />
      </div>
    </div>
    
  2. 2.

加载一个合适的非顶级加载程序 0.5 - 1 秒

class App extends Component {
    state = {
        loading: true
    }
    componentDidMount() {
        setTimeout(() => {
            this.setState({ loading: false });
        }, 1000);
    }
    render() {
        return (
            <React.Fragment>
                {
                    this.state.loading ?
                        <Loader />
                        : (
                            <div className="app">
                                <Header />
                                <MyComponent />
                            </div>
                        )
                }
            </React.Fragment>
        );
    }
}

到目前为止,这种方法效果最好,但如果我发现问题或更好的东西,我会更新

所以只需转到 public 文件夹内的 index.html 和

<div id="root"><-- Add Splash screen html code here --></div>

添加您的启动画面代码,当反应加载时,它会用 id root

替换 div 中的所有内容

我不确定这是否有效,它没有经过测试,但也许它会引导您走向正确的方向?所以,这是我的 2 美分

withSplash.js

const withSplash = MyAppComponent => 
  class extends React.Component {
    state = {
      showSplash: true
    }

    componentDidMount () {
      handleSplashComponent(); 
    }

    componentWillUnmount () {
      if (this.timer) {
        this.timer = null;
      }
    }

    handleSplashComponent = () => {
      this.timer = setTimeout(()=> {
        this.setState({
          showSplash: false
        })
      }, 3000)
    }

    render () {
      return this.state.showSplash
        ? <SplashComponent />
        : <MyAppComponent />
    }
  }

App.js

class App extends Component {
  ...
}

export default withSplash(App);

AnotherComponent.js

class AnotherComponent extends Component {
  ...
}

export default withSplash(AnotherComponent);

这是一个使用 statesetTimeout() 显示加载器五秒钟的示例,您可以使用 splash screen component.

代替 <Loader/>
import React, { Component } from 'react';

import Drawer from '../Drawer/Drawer';
import Loader from '../../components/UI/Spinner/Loader/Loader';

class App extends Component {
  state = {
    loading: true
  }

  componentDidMount(){
    setTimeout(() => {
      this.setState({loading: false});
    }, 5000);
  }

  render() {  
    return (
      <React.Fragment>
        {
          this.state.loading ? <Loader />: <Drawer />
        }
      </React.Fragment>
    );
  }
}

export default App;

希望对您有所帮助!