您好,登錄后才能下訂單哦!
這篇文章給大家介紹如何編寫簡潔的React代碼,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
如果你需要在一個條件為真時有條件地呈現一些東西,在一個條件為假時不呈現任何東西,不要使用三元運算符。使用&&運算符代替。
import React, { useState } from 'react' export const ConditionalRenderingWhenTrueBad = () => { const [showConditionalText, setShowConditionalText] = useState(false) const handleClick = () => setShowConditionalText(showConditionalText => !showConditionalText) return ( <div> <button onClick={handleClick}>Toggle the text</button> {showConditionalText ? <p>The condition must be true!</p> : null} </div> ) }
import React, { useState } from 'react' export const ConditionalRenderingWhenTrueGood = () => { const [showConditionalText, setShowConditionalText] = useState(false) const handleClick = () => setShowConditionalText(showConditionalText => !showConditionalText) return ( <div> <button onClick={handleClick}>Toggle the text</button> {showConditionalText && <p>The condition must be true!</p>} </div> ) }
如果你需要在一個條件為真時有條件地呈現一個東西,在條件為假時呈現另一個東西,請使用三元運算符。
import React, { useState } from 'react' export const ConditionalRenderingBad = () => { const [showConditionOneText, setShowConditionOneText] = useState(false) const handleClick = () => setShowConditionOneText(showConditionOneText => !showConditionOneText) return ( <div> <button onClick={handleClick}>Toggle the text</button> {showConditionOneText && <p>The condition must be true!</p>} {!showConditionOneText && <p>The condition must be false!</p>} </div> ) }
import React, { useState } from 'react' export const ConditionalRenderingGood = () => { const [showConditionOneText, setShowConditionOneText] = useState(false) const handleClick = () => setShowConditionOneText(showConditionOneText => !showConditionOneText) return ( <div> <button onClick={handleClick}>Toggle the text</button> {showConditionOneText ? ( <p>The condition must be true!</p> ) : ( <p>The condition must be false!</p> )} </div> ) }
一個真實的props可以提供給一個組件,只有props名稱而沒有值,比如:myTruthyProp。寫成myTruthyProp={true}是不必要的。
import React from 'react' const HungryMessage = ({ isHungry }) => ( <span>{isHungry ? 'I am hungry' : 'I am full'}</span> ) export const BooleanPropBad = () => ( <div> <span> <b>This person is hungry: </b> </span> <HungryMessage isHungry={true} /> <br /> <span> <b>This person is full: </b> </span> <HungryMessage isHungry={false} /> </div> )
import React from 'react' const HungryMessage = ({ isHungry }) => ( <span>{isHungry ? 'I am hungry' : 'I am full'}</span> ) export const BooleanPropGood = () => ( <div> <span> <b>This person is hungry: </b> </span> <HungryMessage isHungry /> <br /> <span> <b>This person is full: </b> </span> <HungryMessage isHungry={false} /> </div> )
可以用雙引號提供一個字符串道具值,而不使用大括號或反斜線。
import React from 'react' const Greeting = ({ personName }) => <p>Hi, {personName}!</p> export const StringPropValuesBad = () => ( <div> <Greeting personName={"John"} /> <Greeting personName={'Matt'} /> <Greeting personName={`Paul`} /> </div> )
import React from 'react' const Greeting = ({ personName }) => <p>Hi, {personName}!</p> export const StringPropValuesGood = () => ( <div> <Greeting personName="John" /> <Greeting personName="Matt" /> <Greeting personName="Paul" /> </div> )
如果一個事件處理程序只需要事件對象的一個參數,你就可以像這樣提供函數作為事件處理程序:onChange={handleChange}。
你不需要像這樣把函數包在一個匿名函數中。
import React, { useState } from 'react' export const UnnecessaryAnonymousFunctionsBad = () => { const [inputValue, setInputValue] = useState('') const handleChange = e => { setInputValue(e.target.value) } return ( <> <label htmlFor="name">Name: </label> <input id="name" value={inputValue} onChange={e => handleChange(e)} /> </> ) }
import React, { useState } from 'react' export const UnnecessaryAnonymousFunctionsGood = () => { const [inputValue, setInputValue] = useState('') const handleChange = e => { setInputValue(e.target.value) } return ( <> <label htmlFor="name">Name: </label> <input id="name" value={inputValue} onChange={handleChange} /> </> ) }
當把一個組件作為props傳遞給另一個組件時,如果該組件不接受任何props,你就不需要把這個傳遞的組件包裹在一個函數中。
import React from 'react' const CircleIcon = () => ( <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg> ) const ComponentThatAcceptsAnIcon = ({ IconComponent }) => ( <div> <p>Below is the icon component prop I was given:</p> <IconComponent /> </div> ) export const UnnecessaryAnonymousFunctionComponentsBad = () => ( <ComponentThatAcceptsAnIcon IconComponent={() => <CircleIcon />} /> )
import React from 'react' const CircleIcon = () => ( <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg> ) const ComponentThatAcceptsAnIcon = ({ IconComponent }) => ( <div> <p>Below is the icon component prop I was given:</p> <IconComponent /> </div> ) export const UnnecessaryAnonymousFunctionComponentsGood = () => ( <ComponentThatAcceptsAnIcon IconComponent={CircleIcon} /> )
未定義的props被排除在外,所以如果props未定義是可以的,就不要擔心提供未定義的回退。
import React from 'react' const ButtonOne = ({ handleClick }) => ( <button onClick={handleClick || undefined}>Click me</button> ) const ButtonTwo = ({ handleClick }) => { const noop = () => {} return <button onClick={handleClick || noop}>Click me</button> } export const UndefinedPropsBad = () => ( <div> <ButtonOne /> <ButtonOne handleClick={() => alert('Clicked!')} /> <ButtonTwo /> <ButtonTwo handleClick={() => alert('Clicked!')} /> </div> )
import React from 'react' const ButtonOne = ({ handleClick }) => ( <button onClick={handleClick}>Click me</button> ) export const UndefinedPropsGood = () => ( <div> <ButtonOne /> <ButtonOne handleClick={() => alert('Clicked!')} /> </div> )
如果新的狀態依賴于之前的狀態,那么一定要把狀態設置為之前狀態的函數。React的狀態更新可以是分批進行的,如果不這樣寫你的更新就會導致意外的結果。
import React, { useState } from 'react' export const PreviousStateBad = () => { const [isDisabled, setIsDisabled] = useState(false) const toggleButton = () => setIsDisabled(!isDisabled) const toggleButton2Times = () => { for (let i = 0; i < 2; i++) { toggleButton() } } return ( <div> <button disabled={isDisabled}> I'm {isDisabled ? 'disabled' : 'enabled'} </button> <button onClick={toggleButton}>Toggle button state</button> <button onClick={toggleButton2Times}>Toggle button state 2 times</button> </div> ) }
import React, { useState } from 'react' export const PreviousStateGood = () => { const [isDisabled, setIsDisabled] = useState(false) const toggleButton = () => setIsDisabled(isDisabled => !isDisabled) const toggleButton2Times = () => { for (let i = 0; i < 2; i++) { toggleButton() } } return ( <div> <button disabled={isDisabled}> I'm {isDisabled ? 'disabled' : 'enabled'} </button> <button onClick={toggleButton}>Toggle button state</button> <button onClick={toggleButton2Times}>Toggle button state 2 times</button> </div> ) }
以下做法并非針對React,而是在JavaScript(以及任何編程語言)中編寫干凈代碼的良好做法。
將復雜的邏輯提取為明確命名的函數
將神奇的數字提取為常量
使用明確命名的變量
關于如何編寫簡潔的React代碼就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。