React你应该学会的开发技巧【总结】!

前端人

共 9380字,需浏览 19分钟

 · 2021-03-05

来源:betterprogramming.pub/8-ways-to-write-clean-react-code-610c502ccf39


关注公众号 前端人,回复“加群

添加无广告优质学习群


干净的代码不仅仅是工作代码。简洁的代码易于阅读,易于理解并且井井有条。在本文中,我们将研究六种编写更简洁的React代码的方法。

在阅读这些建议时,请务必记住它们的实质:相信这些实践对我们编写自己的React代码很有帮助。让我们一起学习吧!

1.仅针对一种条件渲染

如果你要为某个条件成立时渲染某些元素,请不要使用三元运算符。请改用&&运算符。

不推荐写法:
import React, { useState } from 'react'
export const ConditionalRenderingWhenTrueBad = () => {
  const [showConditionalText, setShowConditionalText] = useState(false)
  const handleClick = () =>
    setShowConditionalText(showConditionalText => !showConditionalText)
    
  return (
    <div>
      <button onClick={handleClick}>切换文本</button>
      {showConditionalText ? <p>成立显示内容</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}>切换文本</button>
      {showConditionalText && <p>成立显示内容!</p>}
    </div>

  )
}

2.Boolean Props简写

isHungry处简写了

不推荐写法:
import React from 'react'
const HungryMessage = ({ isHungry }) => (
  <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
)

export const BooleanPropBad = () => (
  <div>
    <HungryMessage isHungry={true} />
    <HungryMessage isHungry={false} />
  </div>

)

推荐写法:

import React from 'react'
const HungryMessage = ({ isHungry }) => (
  <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
)

export const BooleanPropGood = () => (
  <div>
    <HungryMessage isHungry />
    <HungryMessage isHungry={false} />
  </div>

)

3.String Props简写

personName处简写了

不推荐写法:
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>

)

4.事件处理函数简写

onChange处简写了

不推荐写法:
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} />
    </>

  )
}

5.组件作为参数返回

IconComponent处简写了

不推荐写法:
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>
    <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>
    <IconComponent />
  </div>

)

export const UnnecessaryAnonymousFunctionComponentsGood = () => (
  <ComponentThatAcceptsAnIcon IconComponent={CircleIcon} />
)

6.设置依赖于先前pros的pros

如果新状态依赖于先前状态,则始终将状态设置为先前状态的函数。可以批处理React状态更新,并且不以这种方式编写更新会导致意外结果,setIsDisabled处简写

不推荐写法:
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}>切换按钮状态</button>
      <button onClick={toggleButton2Times}>切换按钮状态2次</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}>切换按钮状态</button>
      <button onClick={toggleButton2Times}>切换按钮状态2次</button>
    </div>

  )
}

接下来你该做的

  • 回复资料包领取我整理的进阶资料包
  • 回复加群,加入前端进阶群
  • console.log("点赞===看===你我都快乐")
  • Bug离我更远了,下班离我更近了
浏览 13
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报