简体   繁体   English

向 React 中的每个组件添加相同代码的最佳方法是什么?

[英]What is the best way to add the same code to every component in React?

I am trying to build a simple page navigation loading screen while using react-router-dom.我正在尝试在使用 react-router-dom 时构建一个简单的页面导航加载屏幕。 My first instinct to start is to do something like:我开始的第一个直觉是做类似的事情:

export default function PageOne = () => {
    
    const [show, setShow] = useState('show');

    useEffect(() => {
        setTimeout(() => {
            setShow('');
        }, 500)
    }, [])    

    return (
        <>
            <div className={`loader ${show}`}></div>
            <div className="PageOne">
                Here is my content for page one
            </div>
        </>
    )
}

Here, the loader div would be displayed with a position: absolute , height: 100vh , and width: 100vw .在这里, loader div 将显示为position: absolute , height: 100vhwidth: 100vw Then after 500ms, it can be animated to fade out or slide off screen.然后在 500 毫秒后,它可以动画淡出或滑出屏幕。

This doesn't feel like a great solution, and it means that the same code will be rewritten within every single page.这感觉不是一个很好的解决方案,这意味着将在每一页中重写相同的代码。 Is there a simpler or more 'reacty' way to do this?有没有更简单或更“反应灵敏”的方法来做到这一点?

Yes, you have the right thinking.是的,你有正确的想法。 To be honest, React is all about code sharing.老实说,React 完全是关于代码共享的。 You can share functions, components, hooks, contexts, etc. There's no right or wrong what you want to share, however if you just want to extract couple of your lines involving useState etc, you can use a hook.您可以共享函数、组件、钩子、上下文等。您要共享的内容没有对错之分,但是如果您只想提取涉及useState等的几行代码,则可以使用钩子。

  const useMyOwnHook = () => { 
    const [show, setShow] = useState('show');

    useEffect(() => {
        setTimeout(() => {
            setShow('');
        }, 500)
    }, [])    

    return show
  }

Then you can use it as然后您可以将其用作

export default function PageOne = () => {
    
    const show = useMyOwnHook() 

    return (
        <>
            <div className={`loader ${show}`}></div>
            <div className="PageOne">
                Here is my content for page one
            </div>
        </>
    )
}

By the way, don't ask me what your code means.顺便说一句,不要问我你的代码是什么意思。 I'm only refactor your code, and that is what a hook is about.我只是重构你的代码,这就是钩子的意义所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM