加入收藏 | 设为首页 | 会员中心 | 我要投稿 大连站长网 (https://www.0411zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 资讯 > 正文

编写简洁的React代码方案

发布时间:2021-05-23 00:06:14 所属栏目:资讯 来源:互联网
导读:副标题#e# 如果你不同意其中任何一条,那也完全没问题。 只对一个条件进行条件性渲染 如果你需要在一个条件为真时有条件地呈现一些东西,在一个条件为假时不呈现任何东西,不要使用三元运算符。使用运算符代替。 糟糕的例子: importReact,{useState}fromrea
副标题[/!--empirenews.page--]

如果你不同意其中任何一条,那也完全没问题。

只对一个条件进行条件性渲染

如果你需要在一个条件为真时有条件地呈现一些东西,在一个条件为假时不呈现任何东西,不要使用三元运算符。使用&&运算符代替。

糟糕的例子:

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> 

  ) 

 Boolean props

一个真实的props可以提供给一个组件,只有props名称而没有值,比如:myTruthyProp。写成myTruthyProp={true}是不必要的。

糟糕的例子:

import React from 'react' 

 

const HungryMessage = ({ isHungry }) => ( 

(编辑:大连站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读