React组件开发流程-03.1

此章先以一个完整的例子来全面了解下React组件开发的流程,主要是以代码为主,在不同的章节中会把重点标出来,要完成的例子如下,也可从官网中找到。
在这里插入图片描述

React组件开发流程

这只是一个通用流程,在熟悉后不需要完全遵从。

  • 将 UI 拆解为组件层级结构
  • 使用 React 构建一个静态版本
  • 找出 UI 精简且完整的 state 表示
  • 验证 state 应该被放置在哪里
  • 添加反向数据流

组件开发流程示例

将 UI 拆解为组件层级结构

在这里插入图片描述

  • FilterableProductTable(灰色)包含完整的应用,最外层元素
    • SearchBar(蓝色)搜索输入框和复选按钮,获取用户输入。
    • ProductTable(淡紫色)产品列表,根据用户输入,展示和过滤清单。
      • ProductCategoryRow(绿色)展示每个类别的表头。
      • ProductRow(黄色)展示每个产品的行。

拆分后构建一种上述的树状结构。

使用 React 构建一个静态版本

在简单的例子中,自上而下构建通常更简单;而在大型项目中,自下而上构建更简单。这里使用自下向上方式构建

ProductCategoryRow

category参数为字符串,如Fruits或Vegetables,从下面的数据中取

{category: “Vegetables”, price: “$1”, stocked: true, name: “Peas”}

function ProductCategoryRow({ category }) {
  return (
      <tr>
        <th colSpan="2">
          {category}
        </th>
      </tr>
  );
}

ProductRow

product参数为是一完整数据,如下面数据

{category: “Vegetables”, price: “$1”, stocked: true, name: “Peas”}

function ProductRow({ product }) {
  const name = product.stocked ? product.name :
      <span style={{ color: 'red' }}>
      {product.name}
    </span>;

  return (
      <tr>
        <td>{name}</td>
        <td>{product.price}</td>
      </tr>
  );
}

ProductTable

products参数为产品数据组,最后返回一个完整的table表格

function ProductTable({ products }) {
  const rows = []; //包含多个ProductCategoryRow组件和ProductRow组件,共同组成一个单独的表格
  let lastCategory = null;

  products.forEach((product) => {
    if (product.category !== lastCategory) {
      rows.push(
          <ProductCategoryRow
              category={product.category}
              key={product.category} />
      );
    }
    rows.push(
        <ProductRow
            product={product}
            key={product.name} />
    );
    lastCategory = product.category;
  });

  return (
      <table>
        <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
        </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
  );
}

SearchBar

无参数,包含一个输入框和一个复选框

function SearchBar() {
  return (
      <form>
        <input type="text" placeholder="Search..." />
        <label>
          <input type="checkbox" />
          {' '}
          Only show products in stock
        </label>
      </form>
  );
}

FilterableProductTable

products参数为产品数据组

function FilterableProductTable({ products }) {
  return (
      <div>
        <SearchBar />
        <ProductTable products={products} />
      </div>
  );
}

发布组件

最顶层组件(FilterableProductTable)将接收数据模型作为其 prop。这被称之为 单向数据流。

const PRODUCTS = [
  {category: "Fruits", price: "$1", stocked: true, name: "Apple"},
  {category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit"},
  {category: "Fruits", price: "$2", stocked: false, name: "Passionfruit"},
  {category: "Vegetables", price: "$2", stocked: true, name: "Spinach"},
  {category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin"},
  {category: "Vegetables", price: "$1", stocked: true, name: "Peas"}
];

export default function App() {
  return <FilterableProductTable products={PRODUCTS} />;
}

找出 UI 精简且完整的 state 表示

有一个规律可以了解下:

  • 随着时间推移 保持不变?如此,便不是 state。
  • 通过 props 从父组件传递?如此,便不是 state。
  • 是否可以基于已存在于组件中的 state 或者 props 进行计算?如此,它肯定不是state!

剩下的可能是 state。所以
让我们再次一条条验证它们:

  • 原始列表中的产品 被作为 props 传递,所以不是 state。
  • 搜索文本似乎应该是 state,因为它会随着时间的推移而变化,并且无法从任何东西中计算出来。
  • 复选框的值似乎是 state,因为它会随着时间的推移而变化,并且无法从任何东西中计算出来。
  • 过滤后列表中的产品 不是 state,因为可以通过被原始列表中的产品,根据搜索框文本和复选框的值进行计算。
  • props 像是你传递的参数 至函数。它们使父组件可以传递数据给子组件,定制它们的展示。举个例子,Form 可以传递 color prop 至 Button。
  • state 像是组件的内存。它使组件可以对一些信息保持追踪,并根据交互来改变。举个例子,Button 可以保持对 isHovered state 的追踪。

验证 state 应该被放置在哪里

验证哪个组件是通过改变 state 实现可响应的,或者 拥有 这个 state。

记住:React 使用单向数据流,通过组件层级结构从父组件传递数据至子组件。要搞清楚哪个组件拥有哪个 state。

验证使用 state 的组件:

  1. ProductTable 需要基于 state (搜索文本和复选框值) 过滤产品列表。
  2. SearchBar 需要展示 state (搜索文本和复选框值)。
  3. 寻找它们的父组件:它们的第一个共同父组件为 FilterableProductTable。

决定 state 放置的地方:我们将过滤文本和勾选 state 的值放置于 FilterableProductTable 中。所以 state 将被放置在 FilterableProductTable。

import { useState } from 'react';

function FilterableProductTable({ products }) {
  const [filterText, setFilterText] = useState('');
  const [inStockOnly, setInStockOnly] = useState(false);

  return (
    <div>
      <SearchBar
        filterText={filterText}
        inStockOnly={inStockOnly} />
      <ProductTable
        products={products}
        filterText={filterText}
        inStockOnly={inStockOnly} />
    </div>
  );
}

然后,filterText 和 inStockOnly 作为 props 传递至 ProductTable 和 SearchBar。

添加反向数据流

简单来讲就是添加事件,当用户更改表单输入时,state 将更新以反映这些更改。state 由 FilterableProductTable 所拥有,所以只有它可以调用 setFilterText 和 setInStockOnly。

function SearchBar({
  filterText,
  inStockOnly,
  onFilterTextChange,
  onInStockOnlyChange
}) {
  return (
    <form>
      <input
        type="text"
        value={filterText}
        placeholder="搜索"
        onChange={(e) => onFilterTextChange(e.target.value)}
      />
      <label>
        <input
          type="checkbox"
          checked={inStockOnly}
          onChange={(e) => onInStockOnlyChange(e.target.checked)}

完整代码如下

这里的事件反向流是用于操作state的,这东西又是私有的,所以需要一个事件函数传递的过程,即

  • 自定义组件FilterableProductTable定义了一个filterText变量;
  • 在FilterableProductTable中包含子组件SearchBar,子组件中有这个输入框,所以需要把filterText的设置函数传递进去;
  • SearchBar 组件需要定义一个参数接收state方法,这个方法供原生的onChange触发
import { useState } from 'react';

function FilterableProductTable({ products }) {
    const [filterText, setFilterText] = useState('');
    const [inStockOnly, setInStockOnly] = useState(false);

    return (
        <div>
            <SearchBar
                filterText={filterText}
                inStockOnly={inStockOnly}
                onFilterTextChange={setFilterText}
                onInStockOnlyChange={setInStockOnly} />
            <ProductTable
                products={products}
                filterText={filterText}
                inStockOnly={inStockOnly} />
        </div>
    );
}

function ProductCategoryRow({ category }) {
    return (
        <tr>
            <th colSpan="2">
                {category}
            </th>
        </tr>
    );
}

function ProductRow({ product }) {
    const name = product.stocked ? product.name :
        <span style={{ color: 'red' }}>
      {product.name}
    </span>;

    return (
        <tr>
            <td>{name}</td>
            <td>{product.price}</td>
        </tr>
    );
}

function ProductTable({ products, filterText, inStockOnly }) {
    const rows = [];
    let lastCategory = null;

    products.forEach((product) => {
        if (
            product.name.toLowerCase().indexOf(
                filterText.toLowerCase()
            ) === -1
        ) {
            return;
        }
        if (inStockOnly && !product.stocked) {
            return;
        }
        if (product.category !== lastCategory) {
            rows.push(
                <ProductCategoryRow
                    category={product.category}
                    key={product.category} />
            );
        }
        rows.push(
            <ProductRow
                product={product}
                key={product.name} />
        );
        lastCategory = product.category;
    });

    return (
        <table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
            </tr>
            </thead>
            <tbody>{rows}</tbody>
        </table>
    );
}

function SearchBar({
                       filterText,
                       inStockOnly,
                       onFilterTextChange,
                       onInStockOnlyChange
                   }) {
    return (
        <form>
            <input
                type="text"
                value={filterText} placeholder="Search..."
                onChange={(e) => onFilterTextChange(e.target.value)} />
            <label>
                <input
                    type="checkbox"
                    checked={inStockOnly}
                    onChange={(e) => onInStockOnlyChange(e.target.checked)} />
                {' '}
                Only show products in stock
            </label>
        </form>
    );
}

const PRODUCTS = [
    {category: "Fruits", price: "$1", stocked: true, name: "Apple"},
    {category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit"},
    {category: "Fruits", price: "$2", stocked: false, name: "Passionfruit"},
    {category: "Vegetables", price: "$2", stocked: true, name: "Spinach"},
    {category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin"},
    {category: "Vegetables", price: "$1", stocked: true, name: "Peas"}
];

export default function App() {
    return <FilterableProductTable products={PRODUCTS} />;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

korgs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值