编写简洁的React代码方案
副问题[/!--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 }) => ( (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |