什么是 React Functional Components? 函数式组件?

发布时间 2023-04-20 17:07:42作者: _eddyz

函数式组件与类组件(Functional Components vs Class Component)

  • 函数式组件只是一个普通 JavaScript 函数,它返回 JSX 对象。
  • 类组件是一个 JavaScript 类,它继承了 React.Component 类,并拥有 render() 方法。

函数式组件举例


import React from "react";

// 1、ES6 新语法的箭头函数
const FunctionalComponent = () => {
  return <h1>Hello, world</h1>;
};

// 2、ES5 的普通函数
function FunctionalComponent() {
  return <h1>Hello, world</h1>;
}

// 带 props 参数的函数式组件
const FunctionalComponent = (props) => {
 return <h1>Hello, {props.name}</h1>;
};

// props 解构的写法
const FunctionalComponent = ({ name }) => {
 return <h1>Hello, {name}</h1>;
};

// 使用:
<FunctionalComponent name="Tom"/>
<FunctionalComponent name="Jack"/>
<FunctionalComponent name="Jimmy"/>

类组件举例

// 解构方式引入 Component 
import React, { Component } from "react";

class ClassComponent extends Component {
 render() {
   return <h1>Hello, world</h1>;
 }
}

// 传统方式
import React from "react";

class ClassComponent extends React.Component {
 render() {
   return <h1>Hello, world</h1>;
 }
}

// 带 props 参数的
class ClassComponent extends React.Component {
  render() {
    const { name } = this.props;
    return <h1>Hello, { name }</h1>;
 }
}

函数式组件基本用法

React 函数式组件是一个简单的 JavaScript 函数,它接受 props 并返回一个 React Element。
在引入 React Hooks 之后,编写函数式组件已经成为现代应用中编写 React 组件的标准方式。

// file: app.js
import React from "react";

/**
 * A functional component (ES6 arrow) called MyComponent
 * that takes props as argument and returns a React
 * element.
 */
const MyComponent = (props) => {
  return (
    <div>Hello {props.name}!</div>
  );
}

/**
 * A functional component called App that returns a 
 * React element.
 */       
function App () {
  return (
    // Passing the name when using the component
    <div>
      <MyComponent name='World'/> 
      <MyComponent name='Educative'/>
    </div>
  );
}

export default App;

// file: index.js
import React from 'react';

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

函数式组件中使用 useState()

const FunctionalComponent = () => {
 const [count, setCount] = React.useState(0);

 return (
   <div>
     <p>count: {count}</p>
     <button onClick={() => setCount(count + 1)}>Click</button>
   </div>
 );
};

函数式组件中使用 useEffect()

使用 useEffect 代替生命周期函数 componentDidMount

const FunctionalComponent = () => {
 React.useEffect(() => {
   console.log("Hello");
 }, []);
 return <h1>Hello, World</h1>;
};

如果 useEffect 返回一个函数,则对应的生命周期函数是 componentWillUnmount

const FunctionalComponent = () => {
 React.useEffect(() => {
   // 返回一个函数,在 componentWillUnmount 时调用。
   return () => {
     console.log("Bye");
   };
 }, []);
 return <h1>Bye, World</h1>;
};

Ref:
https://www.educative.io/answers/what-are-react-functional-components
https://www.twilio.com/blog/react-choose-functional-components