【前端知识】React 基础巩固(十五)——书籍购物车简单案例

React 基础巩固(十五)——书籍购物车简单案例

案例代码

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>购物车案例title>
    <style>
      table {
        border-collapse: collapse;
        text-align: center;
      }

      thead {
        background-color: #f2f2f2;
      }

      td,
      th {
        padding: 10px 16px;
        border: 1px solid grey;
      }
    style>
  head>
  <body>
    <div id="root">div>

    <script
      crossorigin
      src="https://unpkg.com/react@18/umd/react.development.js"
    >script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
    >script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js">script>

    <script src="./data.js">script>
    <script src="./format.js">script>

    <script type="text/babel">
      // 1.创建root
      const root = ReactDOM.createRoot(document.querySelector("#root"));

      // 2.封装App组件
      class App extends React.Component {
        // 组件数据
        constructor() {
          super();
          this.state = {
            books: books,
          };
        }

        // 3.计算总价方式三
        getTotalPrice() {
          const totalPrice = this.state.books.reduce((preValue, item) => {
            return preValue + item.price * item.count;
          }, 0);
          return totalPrice;
        }

        // 增减数量
        changeNumber(idx, count) {
          // 浅拷贝
          const newBooks = [...this.state.books];
          newBooks[idx].count += count;
          this.setState({
            books: newBooks,
          });
        }

        // 删除
        removeItem(idx) {
          // 浅拷贝
          const newBooks = [...this.state.books];
          newBooks.splice(idx, 1);
          this.setState({
            books: newBooks,
          });
        }

        renderBookList() {
          const { books } = this.state;

          // 1.计算总价方式一
          // let totalPrice = 0;
          // for (let i = 0; i < books.length; i++) {
          //   const book = books[i];
          //   totalPrice += book.price * book.count;
          // }

          // 2.计算总价方式二
          // const totalPrice = books.reduce((preValue, item) => {
          //   return preValue + item.price * item.count;
          // }, 0);

          return (
            <div>
              <table>
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>书籍名称</th>
                    <th>出版日期</th>
                    <th>价格</th>
                    <th>购买数量</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {books.map((book, idx) => {
                    return (
                      <tr key={book.id}>
                        <td>{book.id}</td>
                        <td>{book.name}</td>
                        <td>{book.date}</td>
                        <td>{formatPrice(book.price)}</td>
                        <td>
                          <button
                            disabled={book.count <= 1}
                            onClick={() => this.changeNumber(idx, -1)}
                          >
                            -
                          </button>
                          {book.count}
                          <button onClick={() => this.changeNumber(idx, 1)}>
                            +
                          </button>
                        </td>
                        <td>
                          <button onClick={() => this.removeItem(idx)}>
                            删除
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              <h2>总价格:{formatPrice(this.getTotalPrice())}</h2>
            </div>
          );
        }

        renderBookEmpty() {
          return (
            <div>
              <h2>购物车为空,请添加书籍</h2>
            </div>
          );
        }

        // 渲染内容
        render() {
          const { books } = this.state;

          return books.length ? this.renderBookList() : this.renderBookEmpty();
        }
      }

      // 3.渲染组件
      root.render(<App />);
    script>
  body>
html>

书籍数据(data.js)

const books = [
  {
    id: 1,
    name: "《算法导论》",
    date: "2006-9",
    price: 85.0,
    count: 1,
  },
  {
    id: 2,
    name: "《UNIX编程艺术》",
    date: "2006-2",
    price: 59.0,
    count: 1,
  },
  {
    id: 3,
    name: "《编程珠玑》",
    date: "2008-10",
    price: 39.0,
    count: 1,
  },
  {
    id: 4,
    name: "《代码大全》",
    date: "2006-3",
    price: 128.0,
    count: 1,
  },
];

金额标识格式化工具(format.js)

function formatPrice(price) {
  return "¥" + Number(price).toFixed(2);
}

效果图

  • 展示列表
    【前端知识】React 基础巩固(十五)——书籍购物车简单案例_第1张图片

  • 删除书籍
    【前端知识】React 基础巩固(十五)——书籍购物车简单案例_第2张图片

  • 清空书籍文字提示
    【前端知识】React 基础巩固(十五)——书籍购物车简单案例_第3张图片

你可能感兴趣的:(前端知识,React,前端,react.js,javascript)