自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

5個技巧助你編寫更好的React代碼

開發(fā) 前端
在本文中,我分享幾個技巧,這些技巧將改善你的React代碼,希望對你有所幫助!

5個技巧助你編寫更好的React代碼

在本文中,我想分享幾個技巧,這些技巧將改善你的React代碼。

1. 解構(gòu) props

在 JS 中解構(gòu)對象(尤其是 props)可以大大減少代碼中的重復(fù)??聪旅娴睦樱?coffeecard coffee="{item}" key="{item.id}">

  1. //Parent Component 
  2. import React from 'react'
  3.  
  4. import CoffeeCard from './CoffeeCard'
  5.  
  6. const CafeMenu = () => { 
  7.     const coffeeList = [ 
  8.         { 
  9.             id: '0'
  10.             name'Espresso'
  11.             price: '2.00'
  12.             size'16' 
  13.         }, 
  14.         { 
  15.             id: '1'
  16.             name'Cappuccino'
  17.             price: '3.50'
  18.             size'24' 
  19.         }, 
  20.         { 
  21.             id: '2'
  22.             name'Caffee Latte'
  23.             price: '2.70'
  24.             size'12' 
  25.         } 
  26.     ]; 
  27.  
  28.     return coffeeList.map(item => ( 
  29.         <CoffeeCard key={item.id} coffee={item} /> 
  30.     )); 
  31. }; 
  32.  
  33. export default CafeMenu; 

CafeMenu 組件用于存儲可用飲料的列表,現(xiàn)在我們想要創(chuàng)建另一個可以顯示一種飲料的組件。如果不對 props 進行解構(gòu),我們的代碼將像下面這樣: 

  1. //Child Component 
  2. import React from 'react'
  3.  
  4. const CoffeeCard = props => { 
  5.     return ( 
  6.         <div> 
  7.             <h1>{props.coffee.name}</h1> 
  8.             <p>Price: {props.coffee.price}$</p> 
  9.             <p>Size: {props.coffee.size} oz</p> 
  10.         </div> 
  11.     ); 
  12. }; 
  13.  
  14. export default CoffeeCard;  

如你所見,它看起來并不好,每次我們需要獲取某個屬性時,都要重復(fù) props.coffee,幸運的是,我們可以通過解構(gòu)來簡化它。 

  1. //Child Component (after destructuring props) 
  2. import React from 'react'
  3.  
  4. const CoffeeCard = props => { 
  5.     const { name, price, size } = props.coffee; 
  6.     return ( 
  7.         <div> 
  8.             <h1>{name}</h1> 
  9.             <p>Price: {price}$</p> 
  10.             <p>Size: {size} oz</p> 
  11.         </div> 
  12.     ); 
  13. }; 
  14.  
  15. export default CoffeeCard;  

如果我們想將大量參數(shù)傳遞給子組件,我們還可以直接在構(gòu)造函數(shù)(或函數(shù)組件的參數(shù))中解構(gòu) props。比如: 

  1. //Parent Component 
  2. import React from 'react'
  3.  
  4. import ContactInfo from './ContactInfo'
  5.  
  6. const UserProfile = () => { 
  7.     const name = 'John Locke'
  8.     const email = 'john@locke.com'
  9.     const phone = '01632 960668'
  10.  
  11.     return <ContactInfo name={name} email={email} phone={phone} />; 
  12. }; 
  13.  
  14. export default UserProfile; 
  15. //Child Component 
  16. import React from 'react'
  17.  
  18. const ContactInfo = ({ name, email, phone }) => { 
  19.     return ( 
  20.         <div> 
  21.             <h1>{name}</h1> 
  22.             <p> E-mail: {email}</p> 
  23.             <p> Phone: {phone}</p> 
  24.         </div> 
  25.     ); 
  26. }; 
  27.  
  28. export default ContactInfo; 

2. 保持導(dǎo)入模塊的順序

有時(尤其是在“容器組件”中),我們需要使用許多不同的模塊,并且組件導(dǎo)入看上去有些混亂,如:

  1. import { Auth } from 'aws-amplify'
  2. import React from 'react'
  3. import SidebarNavigation from './components/SidebarNavigation'
  4. import { EuiPage, EuiPageBody } from '@elastic/eui'
  5. import { keyCodes } from '@elastic/eui/lib/services'
  6. import './index.css' 
  7. import HeaderNavigation from './components/HeaderNavigation'
  8. import Routes from './Routes'

關(guān)于導(dǎo)入模塊的理想順序有很多不同的觀點。我建議多參考,然后找到適合你自己的那種。

至于我自己,我通常按類型對導(dǎo)入進行分組,并按字母順序?qū)λ鼈冞M行排序(這是可選操作)。我也傾向于保持以下順序:

  1. 標(biāo)準(zhǔn)模塊
  2. 第三方模塊
  3. 自己代碼導(dǎo)入(組件)
  4. 特定于模塊的導(dǎo)入(例如CSS,PNG等)
  5. 僅用于測試的代碼

快速重構(gòu)一下,我們的模塊導(dǎo)入看上去舒服多了了。

  1. import React from 'react'
  2.  
  3. import { Auth } from 'aws-amplify'
  4. import { EuiPage, EuiPageBody } from '@elastic/eui'
  5. import { keyCodes } from '@elastic/eui/lib/services'
  6.  
  7. import HeaderNavigation from './components/HeaderNavigation'
  8. import SidebarNavigation from './components/SidebarNavigation'
  9. import Routes from './Routes'
  10.  
  11. import './index.css' 

3.使用 Fragments

在我們的組件中,我們經(jīng)常返回多個元素。一個 React 組件不能返回多個子節(jié)點,因此我們通常將它們包裝在 div 中。有時,這樣的解決方案會有問題。比如下面的這個例子中:

我們要創(chuàng)建一個 Table 組件,其中包含一個 Columns 組件。 

  1. import React from 'react' 
  2. import Columns from './Columns'
  3.  
  4. const Table = () => { 
  5.     return ( 
  6.         <table
  7.             <tbody> 
  8.                 <tr> 
  9.                     <Columns /> 
  10.                 </tr> 
  11.             </tbody> 
  12.         </table
  13.     ); 
  14. }; 
  15.  
  16. export default Table 

Columns 組件中包含一些 td 元素。由于我們無法返回多個子節(jié)點,因此需要將這些元素包裝在 div 中。

  1. import React from 'react' 
  2. const Columns = () => { 
  3.     return ( 
  4.         <div> 
  5.             <td>Hello</td> 
  6.             <td>World</td> 
  7.         </div> 
  8.     ); 
  9. }; 
  10.  
  11. export default Columns; 

然后就報錯了,因為tr 標(biāo)簽中不能放置 div。我們可以使用 Fragment 標(biāo)簽來解決這個問題,如下所示:

  1. import React, { Fragment } from 'react'
  2. const Columns = () => { 
  3.     return ( 
  4.         <Fragment> 
  5.             <td>Hello</td> 
  6.             <td>World</td> 
  7.         </Fragment> 
  8.     ); 
  9. }; 
  10.  
  11. export default Columns; 

我們可以將 Fragment 視為不可見的 div。它在子組件將元素包裝在標(biāo)簽中,將其帶到父組件并消失。

你也可以使用較短的語法,但是它不支持 key 和屬性。 

  1. import React from 'react' 
  2. const Columns = () => { 
  3.     return ( 
  4.         <> 
  5.             <td>Hello</td> 
  6.             <td>World</td> 
  7.         </> 
  8.     ); 
  9. }; 
  10. export default Columns; 

4. 使用展示組件和容器組件

將應(yīng)用程序的組件分為展示(木偶)組件和容器(智能)組件。如果你不知道這些是什么,可以下面的介紹:

展示組件

  • 主要關(guān)注UI,它們負(fù)責(zé)組件的外觀。
  • 數(shù)據(jù)由 props 提供,木偶組件中不應(yīng)該調(diào)用API,這是智能組件的工作
  • 除了UI的依賴包,它們不需要依賴應(yīng)用程序
  • 它們可能包括狀態(tài),但僅用于操縱UI本身-它們不應(yīng)存儲應(yīng)用程序數(shù)據(jù)。

木偶組件有:加載指示器,模態(tài),按鈕,輸入。

容器組件

  • 它們不關(guān)注樣式,通常不包含任何樣式
  • 它們用于處理數(shù)據(jù),可以請求數(shù)據(jù),捕獲更改和傳遞應(yīng)用程序數(shù)據(jù)
  • 負(fù)責(zé)管理狀態(tài),重新渲染組件等等
  • 可能依賴于應(yīng)用程序,調(diào)用 Redux,生命周期方法,API和庫等等。

使用展示組件和容器組件的好處

  • 更好的可讀性
  • 更好的可重用性
  • 更容易測試

此外,它還符合“單一責(zé)任原則” - 一個組件負(fù)責(zé)外觀,另一個組件負(fù)責(zé)數(shù)據(jù)。

示例

讓我們看一個簡單的例子。這是一個 BookList 組件,該組件可從API獲取圖書數(shù)據(jù)并將其顯示在列表中。 

  1. import React, { useState, useEffect } from 'react' 
  2. const BookList = () => { 
  3.     const [books, setBooks] = useState([]); 
  4.     const [isLoading, setLoading] = useState(false); 
  5.  
  6.     useEffect(() => { 
  7.         setLoading(true); 
  8.         fetch('api/books'
  9.             .then(res => res.json()) 
  10.             .then(books => { 
  11.                 setBooks(books); 
  12.                 setLoading(false); 
  13.             }); 
  14.     }, []); 
  15.  
  16.     const renderLoading = () => { 
  17.         return <p>Loading...</p>; 
  18.     }; 
  19.  
  20.     const renderBooks = () => { 
  21.         return ( 
  22.             <ul> 
  23.                 {books.map(book => ( 
  24.                     <li>{book.name}</li> 
  25.                 ))} 
  26.             </ul> 
  27.         ); 
  28.     }; 
  29.  
  30.     return <>{isLoading ? renderLoading() : renderBooks()}</>; 
  31. }; 
  32. export default BookList;  

該組件的問題在于,它負(fù)責(zé)太多事情。它獲取并呈現(xiàn)數(shù)據(jù)。它還與一個特定的接口關(guān)聯(lián),因此在不復(fù)制代碼的情況下,不能使用此組件顯示特定用戶的圖書列表。

現(xiàn)在,讓我們嘗試將此組件分為展示組件和容器組件。 

  1. import React from 'react'
  2.  
  3. const BookList = ({ books, isLoading }) => { 
  4.     const renderLoading = () => { 
  5.         return <p>Loading...</p>; 
  6.     }; 
  7.  
  8.     const renderBooks = () => { 
  9.         return ( 
  10.             <ul> 
  11.                 {books.map(book => ( 
  12.                     <li key={book.id}>{book.name}</li> 
  13.                 ))} 
  14.             </ul> 
  15.         ); 
  16.     }; 
  17.  
  18.     return <>{isLoading ? renderLoading() : renderBooks()}</>; 
  19. }; 
  20. export default BookList; 
  21. import React, { useState, useEffect } from 'react'
  22. import BookList from './BookList'
  23.  
  24. const BookListContainer = () => { 
  25.     const [books, setBooks] = useState([]); 
  26.     const [isLoading, setLoading] = useState(false); 
  27.  
  28.     useEffect(() => { 
  29.         setLoading(true); 
  30.         fetch('/api/books'
  31.             .then(res => res.json()) 
  32.             .then(books => { 
  33.                 setBooks(books); 
  34.                 setLoading(false); 
  35.             }); 
  36.     }, []); 
  37.  
  38.     return <BookList books={books} isLoading={isLoading} />; 
  39. }; 
  40.  
  41. export default BookListContainer;  

5. 使用 styled-components

對 React 組件進行樣式設(shè)置一直是個難題。查找拼寫錯誤的類名,維護大型 CSS 文件,處理兼容性問題有時可能很痛苦。

styled-components 是一個常見的 css in js 類庫,和所有同類型的類庫一樣,通過 js 賦能解決了原生 css 所不具備的能力,比如變量、循環(huán)、函數(shù)等。

要開始使用 styled-components,你需要首先安裝依賴: 

  1. npm i styled-components 

下面是一個示例: 

  1. import React from 'react'
  2. import styled from 'styled-components'
  3.  
  4. const Grid = styled.div` 
  5.     display: flex; 
  6. `; 
  7.  
  8. const Col = styled.div` 
  9.     display: flex; 
  10.     flex-direction: column
  11. `; 
  12.  
  13. const MySCButton = styled.button` 
  14.     background: ${props => (props.primary ? props.mainColor : 'white')}; 
  15.     color: ${props => (props.primary ? 'white' : props.mainColor)}; 
  16.     display: block; 
  17.     font-size: 1em; 
  18.     margin: 1em; 
  19.     padding: 0.5em 1em; 
  20.     border: 2px solid ${props => props.mainColor}; 
  21.     border-radius: 15px; 
  22. `; 
  23.  
  24. function App() { 
  25.     return ( 
  26.         <Grid> 
  27.             <Col> 
  28.                 <MySCButton mainColor='#ee6352' primary>My 1st Button</MySCButton> 
  29.                 <MySCButton mainColor='#ee6352'>My 2st Button</MySCButton> 
  30.                 <MySCButton mainColor='#ee6352'>My 3st Button</MySCButton> 
  31.             </Col> 
  32.             <Col> 
  33.                 <MySCButton mainColor='#515052' primary>My 4st Button</MySCButton> 
  34.                 <MySCButton mainColor='#515052'>My 5st Button</MySCButton> 
  35.                 <MySCButton mainColor='#515052'>My 6st Button</MySCButton> 
  36.             </Col> 
  37.         </Grid> 
  38.     ); 
  39.  
  40. export default App; 

這只是樣式化組件如何工作的一個簡單示例,但是它們可以做的還遠遠不止這些。你可以在其官方文檔中了解有關(guān)樣式化組件的更多信息。 

 

責(zé)任編輯:龐桂玉 來源: 前端大全
相關(guān)推薦

2013-04-17 09:32:31

2020-06-23 07:50:13

Python開發(fā)技術(shù)

2020-06-23 07:48:18

Python開發(fā)技術(shù)

2020-10-04 13:15:37

代碼技術(shù)開發(fā)

2020-08-06 00:25:38

Python代碼開發(fā)

2020-08-06 16:34:48

Python開發(fā)工具

2010-12-01 09:15:35

基礎(chǔ)架構(gòu)

2014-07-29 13:55:10

程序員代碼

2017-08-30 11:10:25

代碼

2021-03-17 08:00:59

JS語言Javascript

2016-12-13 10:06:25

編寫Java單元測試技巧

2017-08-30 19:32:08

代碼程序員編程

2017-09-14 12:45:35

2025-01-14 00:01:01

2022-12-07 15:01:47

2014-04-21 10:14:52

PromisesJavaScript

2022-06-08 08:55:15

JavaScript代碼前端

2023-10-10 08:00:00

2021-04-25 11:31:45

React代碼整潔代碼的實踐

2024-01-30 08:54:05

JavaScript技巧代碼
點贊
收藏

51CTO技術(shù)棧公眾號