学习如何在 React 中偷懒:初学者指南。

2025-06-07

学习如何在 React 中偷懒:初学者指南。

如果你经常阅读开发文章,你可能听过一两次(或者根据人群而反复听到)这样一句话:最优秀的开发人员都是懒人!他们用尽可能少的复杂度完成尽可能多的工作,同时保持代码的可读性。

对我们来说幸运的是,反应方式优先考虑组合而不是继承(即使用组件),这鼓励我们尽可能地懒惰(和高效)。

那么,英语中的成分是什么?

零部件就是工具。零部件就是修理汽车电池时用来拧紧端子的扳手。有时你需要12号的扳手,所以你会给它一个“12”的支柱。有时,根据具体问题,你需要稍大或稍小一点的尺寸。

在稍微慢一点的日子里,你可以把组件比作一口锅或煎锅。如果你需要煎两个鸡蛋,那么你不需要一个大锅(或者用 React 的话说,你不需要 'large' 属性)。你可以传递 'small' 属性,根据需要煎鸡蛋,然后享受 React 带来的乐趣。

在您看到的小事情中,如果您是初学者,只是学习“以反应思考”的诀窍,则可能需要几周甚至几个月的时间才能完全掌握并开始利用可重用组件的强大功能。

本文兼教程将通过构建可重复使用的组件来帮助您。

间隔组件又称为“Shift-abeg”

如果你不明白这个别名的含义,别担心,它是尼日利亚俚语,意思是“给我点空间”。我发现,让你的代码尽可能地通俗易懂,能让你更快地理解。

两只狐狸打架

两只狐狸互相叫道“请移步”
照片由 cloudvisual.co.uk 在 Unsplash 上拍摄

假设你是一名前端开发者,需要给很多东西添加外边距。运气好的话,大多数流行的 CSS 库都能帮你搞定。但话说回来,你肯定不想像个拿着火箭筒去打仗的人一样……有时候,一个简单的原生外边距属性就能搞定。

所以你到处都在用 margin 属性,把它添加到你的组件类中,你讨厌额外的输入,但是你能做什么呢?简而言之:“偷懒!”

如果您可以制作一个可以接受道具的组件,该道具可以通过最少的指令确定您想要多少空间,那会怎样?

步骤 1:创建我们的组件脚手架。

import React from 'react'

export default Spacer = () => {}


Enter fullscreen mode Exit fullscreen mode

第 2 步:赋予它行为

import React from 'react'

export default Spacer = () => {
return(
<div style={{margin: ""}}></div>
)
}


Enter fullscreen mode Exit fullscreen mode

在这种情况下,我们不希望我们的组件帮我们修理汽车或煎两个鸡蛋......尽管这些现在很棒,但我们只是希望在应用它时有一些空间。

步骤3:传递一些道具。

如果您在听到 props 时头脑变得混乱,它只是 property 的缩写...就像一个对象如何具有属性(或键)以及与该prop关联的值?

import React from 'react'

export default Spacer = (props) => {
return(
<div style={{margin: props.unit }}>{props.children}</div>
)
}


Enter fullscreen mode Exit fullscreen mode

等一下,我以为我们想要空间,为什么我们的组件有孩子?!

现在让我们冷静一下,我们的组件需要有子元素,是因为我们不想让组件关心它把创建空间的能力应用到什么地方。我们只希望它是一个公正、无偏见的Shift-abeg(er)。所以“子元素”的本质是,你不会事先知道会得到什么,但无论它是什么,都要给它应用一个 margin 属性。

接下来,我们的 unit props 属性才是真正神奇的地方。现在,我们希望Shift-abeg组件能够为它传入的数字(以像素为单位)提供一个边距。现在,Spacer 还不知道这个属性应该是一个数字,所以我们请求一个之前支持“date” react 的包的帮助,但后来他们解散了。我知道这很令人难过。

这个包叫做“prop-types”。它用于检查 props 的数据类型,这样你的组件就能知道何时传递了正确的 props,反之亦然。

安装 prop-types...

 npm install prop-types  || yarn add prop-types
Enter fullscreen mode Exit fullscreen mode

安装完成后,我们将其添加到我们的组件中,让它了解作为单位道具应该接收什么。

import React from 'react';
import PropTypes from 'prop-types';

export default Spacer = (props) => {
return(
<div style={{margin: props.unit }}>{props.children}</div>
)
}


Spacer.propTypes = {
   unit: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
}

Enter fullscreen mode Exit fullscreen mode

别慌!我们只是告诉组件,当我们想要添加 unit="5px" 或 unit="5em" 等内容时,它应该接收一个字符串;而当我们只想执行以下操作时,它应该接收一个数字:unit={5}。

我们的 Spacer 组件快完成了!

现在,我们的间隔组件已经可以设置外边距了,但如果我们想要左外边距或右外边距呢?它就不行了。我们是不是已经尽力偷懒了?

让我们更进一步:

import React from 'react';
import PropTypes from 'prop-types';

export default Spacer = (props) => {
return(
<div style={{
   margin: props.unit,
   marginLeft: props.left,
   marginRight: props.right,
}}>
   {props.children}
</div>
)
}


Spacer.propTypes = {
   unit: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   left: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   right: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   children: PropTypes.elementType
}

Enter fullscreen mode Exit fullscreen mode

Proptypes.elementType means: "hey Spacer, expect your children props to be react elements"

太棒了!(此处俚语意为“太棒了!”)我们快完成了。现在,我们的 Spacer 可以赋予传递给它的任何子组件向左或向右移动的能力。

但有一个小问题...

如果没有传递任何值怎么办?我们没有针对该事件的回退机制。例如,如果我们设置了 margin-left 属性,因为这是我们想要的行为,那么 margin 和 margin-right 属性会如何处理呢?

让我们修复这个问题:

import React from 'react';
import PropTypes from 'prop-types';

export default Spacer = (props) => {
return(
<div style={{
   margin: props.unit || "",
   marginLeft: props.left || "",
   marginRight: props.right || "",
}}>
   {props.children}
</div>
)
}


Spacer.propTypes = {
   unit: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   left: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   right: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   children: PropTypes.elementType
}

Enter fullscreen mode Exit fullscreen mode

好了!我们已经确保,即使没有向组件的任何样式属性传递任何内容,组件也不会抛出错误。

先生,顶部和底部的边距怎么样?

妙就妙在这儿,如果你想在组件顶部或底部留出空间,你无需传递任何子元素。你只需传递一个unitprop,指定你想要的像素大小,然后将其放置在目标组件的顶部或底部即可。

垫片实际作用:

import React from 'react';
import Spacer from './components/common/Spacer'; 

const App = () => {

return (
  <div>
  <Spacer unit={40}/>
  <ComponentThatNeedsAMarginTopProperty />
  </div>
)

}


export default App;
Enter fullscreen mode Exit fullscreen mode

对于正常保证金权力:

import React from 'react';
import Spacer from './components/common/Spacer'; 

const App = () => {
//This would give it space to the left side of the component!
return (
  <div>
  <Spacer left={40}>
  <ComponentThatNeedsAMarginLeftProperty /> 
  </Spacer>
  </div>
)

}


export default App;
Enter fullscreen mode Exit fullscreen mode



A side note(updated):
Please note that using the style property of jsx tags give them more power over your styles than classes. This could lead to issues that make css hard to debug, classes are better as rightly pointed out in the comments section. However for the purpose of keeping this tutorial as beginner-friendly as possible, I'll leave as is.
</code> 


##Laziness is Achieved!
Congrats dear beginner! You've made a reusable component! Now the amount of time you spend writing margin-this or margin-that for classes have reduced significantly. You can now spend more time on other parts of your code! This is just a brief introduction to the power of re-usability to the uninitiated in React. Hope this helped. 

Stay lazy.
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/itz_giddy/learning-how-to-be-lazy-in-react-a-guide-for-beginners-4gp5
PREV
在 React 项目中设置 Jest 和 React 测试库 | 分步指南
NEXT
面向前端开发人员的 UI/UX 技巧(第一部分)