React 函数组件
本文最后更新于 518 天前,其中的信息可能已经有所发展或是发生改变。

React 函数组件

1、定义方式

React 函数组件是指使用函数方法定义的组件。
定义方式:与函数的定义方式相同,需要将内容 return 出来,需要注意的是最外层只有一个标签或者使用<></>(Fragment 标签)包裹起来,方法写在 return 前面。

const App = () => {
  const getData = () => {
    return [1, 2, 3, 4, 5];
  };
  return (
    <>
      <h1>一级标题</h1>
      <h2>二级标题</h2>
      <h2>{getData()}</h2>
    </>
  );
};
export default App;

2、React Hook

由于 React 的函数组件没有生命周期。所以我们使用 Hook 来更改变量和进行数据操作。
在项目中最常用的 hook 如 useState、useEffect 以及 useRef。

2.1 useState

点击 add 数字加一,点击 sub 数字减一

import React, { useState } from "react";
export default App = () => {
  const [count, setCount] = useState(0);
  // 这里表示定义一个count变量,初始值为0;setCount表示对改变量进行赋值。
  return (
    <>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>add</button>
      <button onClick={() => setCount(count - 1)}>sub</button>
    </>
  );
};

上述代码等同于

import React from "react";
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  render() {
    const { count } = this.state;
    return (
      <>
        <p>{count}</p>
        <button onClick={() => this.setState({ count: count + 1 })}>add</button>
        <button onClick={() => this.setState({ count: count - 1 })}>sub</button>
      </>
    );
  }
}

2.2 useRef

useRef 可以用于定义一个全局变量或者用于获取 DOM 元素

import React, { useRef } from "react";
export default App = () => {
  const pRef = useRef("0");
  const inputRef = useRef(null);
  const add = () => {
    pRef.current = pRef.current + 1; // 不生效
  };
  return (
    <>
      <input ref={inputRef} type="text" value="1" />
      <p>{pRef.current}</p>
      <button onclick={add}>add</button>
    </>
  );
};

2.3 useEffect

useEffect 可以看作 class 组件中的 componentDidMount 和 componentDidUpdate 函数

import React, { useState, useEffect } from "react";
const [status, setStatus] = useState(false);
const [data, setData] = useState([]);

export default App = () => {
  const [status, setStatus] = useState(false);
  const [data, setData] = useState([]);
  useEffect(() => {
    setData([2, 3]);
  }, []); // 在页面刚渲染完成执行(componentDidMount)

  useEffect(() => {
    console.log("data:", data);
  }, status); // 每当status改变时,执行代码

  const change = () => {
    setStatus(false);
    if (data) {
      setData([...data, data.push(1)]);
      setStatus(true);
    }
  };
  return (
    <>
      <p>{data}</p>
      <button onClick={change}>add</button>
    </>
  );
};

3、Antd 中 modal 和 form 组件

Modal 和 Form 一起配合使用时,设置 destroyOnClose 也不会在 Modal 关闭时销毁表单字段数据,需要设置 Form 组件的 preserve={false}

import { Table, Button, Form, Input, Modal } from "antd";
import React, { useState, useEffect } from "react";
const FormButton = ({ open, onCancel, record, getData }) => {
  const [form] = Form.useForm();
  const onFinish = (values) => {
    getData(values);
  };
  return (
    <Modal
      open={open}
      onCancel={onCancel}
      width={300}
      footer={null}
      destroyOnClose
    >
      <Form
        form={form}
        onFinish={onFinish}
        preserve={false}
        initialValues={record}
      >
        <Form.Item name="title" label="标题">
          <Input />
        </Form.Item>
        <Form.Item name="content" label="内容">
          <Input type="textarea" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
          <Button
            htmlType="button"
            onClick={onCancel}
            style={{ margin: "0 8px" }}
          >
            取消
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};
const App = () => {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState(
    JSON.stringify({
      title: "公告",
      content: "明天放假一天,注意时间分配",
    })
  );
  const onCancel = () => {
    setOpen(false);
  };

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      width: "200",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
      width: "200",
    },
  ];
  const getData = (val) => {
    console.log("提交的数据是:", val);
    if (val) {
      setOpen(false);
      setData(JSON.stringify(val));
    }
    return data;
  };
  useEffect(() => {
    getData();
  }, []);
  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setOpen(true);
        }}
      >
        修改
      </Button>
      <FormButton
        open={open}
        record={JSON.parse(data)}
        onCancel={onCancel}
        getData={getData}
      />
      <Table dataSource={[JSON.parse(data)]} columns={columns} />
    </div>
  );
};
export default App;
本文链接:https://likepoems.com/articles/react-function-component/
转载说明:本站文章若无特别说明,皆为原创,转载请注明来源:likepoems,谢谢!^^
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇