编写 React 组件的 6 种方法(包括 TS)
大家好,我叫马特奥 (Mateo)。和大家一样,新年伊始,我设定了一些目标。分享、记录和运用我的知识就是其中的一部分,所以我决定开设一个名为 的空间Coding with Mateo
。
我的第一篇文章将整理 React 组件的各种编写方法。此外,我会保留它的 Typescript 版本,以便于理解如何在不同的呈现方式中注释函数。让我们开始吧。
React 逐渐成为我们谈到前端开发时想到的范式/技术。看一些视频,买一些 Udemy 课程,列出你的第一份任务清单,最终掌握主要概念。然而,JavaScript 提供的语法多样性,有时让我们无法理解为什么有些人用一种方式编写组件,而另一些人用另一种方式。
重要的是要记住:
-
React 组件是一种函数,由于其组合,它可以包含内部函数,包括新组件。
-
Javascript 函数是对象,不同之处在于它们可以通过括号执行。
-
即使您仍在维护/编写类组件,这些组件也会被解释、转置和执行为 ES5 函数,因为这些类只是最近的 EcmaScript 功能的语法糖。
无论您是独自一人还是在团队中开展项目,定义一种语法来声明您的实用程序函数和 React 组件都可以帮助简化因项目结构快速增长而造成的疲劳。
下面,我以按钮为例向您展示编写 React 组件的不同方法。
1.使用常规的function
。
// Button.jsx
function Button (props) {
return <button>{props.children}</button>
}
// Button.tsx
type ButtonProps = {
children: React.ReactNode;
};
function Button (props: ButtonProps) {
return <button>{props.children}</button>
}
2.使用function
表达式。
// Button.jsx
const Button = function (props) {
return <button>{props.children}</button>
}
// Button.tsx
type ButtonProps = {
children: React.ReactNode;
};
const Button = function (props: ButtonProps) {
return <button>{props.children}</button>
}
3.使用arrow function
with const
。
// Button.jsx
const Button = (props) => {
return <button>{props.children}</button>
}
// Button.tsx
type ButtonProps = {
children: React.ReactNode;
};
const Button = (props: ButtonProps) => {
return <button>{props.children}</button>
}
4.使用arrow function
with let
。
// Button.jsx
let Button = (props) => {
return <button>{props.children}</button>
}
// Button.tsx
type ButtonProps = {
children: React.ReactNode;
};
let Button = (props: ButtonProps) => {
return <button>{props.children}</button>
}
5.使用explicit return
// Button.jsx
let Button = (props) => <button>{props.children}</button>
// or
const Button = (props) => <button>{props.children}</button>
// Button.tsx
type ButtonProps = {
children: React.ReactNode;
};
let Button = (props: ButtonProps) => <button>{props.children}</button>
6.使用class
。
// Button.jsx
class Button extends React.Component {
render () {
return <button>{this.props.children}</button>
}
}
// Button.tsx
type ButtonProps = {
children: React.ReactNode;
};
class Button extends React.Component<ButtonProps> {
render() {
return <button>{this.props.children}</button>;
}
}
最后,我必须说,所有的写作方法都很有效。没有哪一种比另一种更好,你可以随意使用你最喜欢的一种。
不过,我想澄清的是:
function ThisOrThat (props) {
/*
Maybe some difficult logic.
Of course, that code does not smell good, however, it's
important to know that's possible to do this.
*/
let renderedComponent = getComplexComponent(props); //
if (!renderedComponent) {
renderedComponent = <FallbackComponent />
}
return <section>{renderedComponent}</section>
}
我很想知道您的意见,以及您希望在我的博客文章中看到哪些主题。如果您能react
访问我的博客,我会非常高兴。
非常感谢,新年快乐🎉🥳
文章来源:https://dev.to/mateo_garcia/6-ways-to-write-a-react-component-ts-included-2k42