react hooks使用
One of my projects uses a library called Fixed-Data-Table-2 (FDT2), and it’s great for efficiently rendering tons of rows of data.
我的一个项目使用了一个名为Fixed-Data-Table-2 (FDT2)的库,它对于有效地呈现大量数据行非常有用。
Their documentation demonstrates a responsive table that resizes based on the browser’s width and height.
他们的文档演示了一个响应表 ,该表根据浏览器的宽度和高度进行调整。
![](https://i-blog.csdnimg.cn/blog_migrate/323aa7962171e02b785bb0e852f878fa.png)
I thought it’d be cool to share this example using React Hooks.
我认为使用React Hooks分享这个例子很酷。
什么是React Hooks? (What are React Hooks?)
They’re functions that give you React features like state and lifecycle hooks without ES6 classes.
它们是为您提供React功能的功能,例如没有ES6类的状态和生命周期挂钩。
Some benefits are
一些好处是
- isolating stateful logic, making it easier to test 隔离状态逻辑,使其更易于测试
- sharing stateful logic without render props or higher-order components 共享状态逻辑而无需渲染道具或高阶组件
- separating your app’s concerns based on logic, not lifecycle hooks 根据逻辑而非生命周期挂钩来分离应用程序的关注点
avoiding ES6 classes, because they’re quirky, not actually classes, and trip up even experienced JavaScript developers
避免使用ES6类,因为它们很古怪, 而不是真正的类 ,甚至会绊倒有经验JavaScript开发人员
For more detail see React’s official Hooks intro.
有关更多详细信息,请参见React的官方Hooks介绍 。
警告:请勿在生产中使用! (WARNING: Don’t use in production!)
At the time of this writing, Hooks are in alpha. Their API can change at any time.
在撰写本文时, Hooks处于alpha状态。 他们的API可以随时更改。
I recommend you experiment, have fun, and use Hooks in your side projects, but not in production code until they’re stable.
我建议您尝试一下,玩得开心,并在您的辅助项目中使用Hook,但要在稳定之前再在生产代码中使用它们。
目标 (The goal)
![](https://i-blog.csdnimg.cn/blog_migrate/50d5deddfe86a58d320647df05b8557b.png)
We’ll be building a responsive Fixed-Data-Table. It won’t be too narrow or too wide for our page, it’ll fit just right!
我们将构建一个响应式固定数据表。 它对于我们的页面来说不会太窄或太宽,它恰好适合!
建立 (Setup)
Here are the GitHub and CodeSandbox links.
这是GitHub和CodeSandbox链接。
git clone https://github.com/yazeedb/Responsive-FDT2-Hooks/
cd Responsive-FDT2-Hooks
npm install
The master
branch has the finished project, so checkout the start
branch if you wish to follow along.
master
分支具有完成的项目,因此,如果您希望继续,请签出start
分支。
git checkout start
git checkout start
And run the project.
并运行该项目。
npm start
npm start
Th