React JSX搭建并实现一个示例项目

小豆苗 9月前 ⋅ 695 阅读

废话不多说,直接写步骤:

  • 新建项目

首先我们需要使用npm init初始化一个项目。

mkdir react-demo
cd react-demo
npm init -y # -y 表示使用默认配置

命令执行完成之后,将生成一个package.json文件,npm是通过这个文件来管理我们项目的依赖的。

接着我们可以使用npm install来安装React相关的类库。

npm install react react-dom serve

接着我们在react-demo文件夹下面,创建srcdistdata,分别用于存放源代码信息、编译后的代码信息以及数据信息。

mkdir src
mkdir dist
mkdir data

我们在开发React应用时,基本组成单元都是以React组件方式呈现的。所以需要在创建一个src/components文件夹用于存在React组件。

mkdir src/components
  • 构建应用

最基础的组件进行实现开发,首先来开发Instructions.js组件。

import React from "react";

export default function Instructions({ title, steps }) {
    return (
        <section className="instructions">
            <h2>{title}</h2>
            {steps.map((s, i) => (
                <p key={i}>{s}</p>
            ))}
        </section>
    );
}

该组件包含两个参数,一个是名称,另一个是步骤。

接下来我们再来构建Ingredient.js组件。

import React from "react";

export default function Ingredient({ amount, measurement, name }) {
    return (
        <li>
            {amount} {measurement} {name}
        </li>
    );
}

该组件支持三个参数,分别是量、单位和名称。

有了配料组件之后,我们可以构建IngredientList.js组件,来构建一个配置列表。

import React from "react";
import Ingredient from './Ingredient';

export default function IngredientList({ list }) {
    return (
        <ul className="ingredients">
            {list.map((ingredient , i) => {
                <Ingredient key={i} {...ingredient} />
            })}
        </ul>
    )
}

这里我们引入了Ingredient组件,将参数list中每一个元素通过展开运算符传入Ingredient组件中。

有了配料和说明之后,我们可以使用这些组件来构建Recipe.js组件。

import React from "react";
import IngredientList from "./IngredientList";
import Instructions from './Instructions';

function Recipe({ name, ingredients, steps}) {
    return (
        <section id={name.toLowerCase().replace(/ /g, "-")}>
            <h1>{name}</h1>
            <IngredientList list={ingredients}/>
            <Instructions title="Cooking Instructions" steps={steps}/>
        </section>
    );
}

export default Recipe;

最后,我们再通过Recipe组件来组装Menu组件。

import React from "react";
import Recipe from './Recipe';

function Menu({recipes}) {
    return (
        <article>
            <header>
                <h1>Delicious Recipes</h1>
            </header>
            <div className="recipes">
                {recipes.map((recipe, i) => (
                    <Recipe key={i} {...recipe} />
                ))}
            </div>
        </article>
    );
}

export default Menu;

好了需要的组件基本都写好了。我们为菜单准备了一份json数据recipes.json,存储在data文件夹中。

[
    {
        "name": "Baked Salmon",
        "ingredients": [
            { "name": "Salmon", "amount": 1, "measurement": "lb" },
            { "name": "Pine Nuts", "amount": 1, "measurement": "cup" },
            { "name": "Butter Lettuce", "amount": 2, "measurement": "cups" },
            { "name": "Yellow Squash", "amount": 1, "measurement": "med" },
            { "name": "Olive Oil", "amount": 0.5, "measurement": "cup" },
            { "name": "Garlic", "amount": 3, "measurement": "cloves" }
        ],
        "steps": [
            "Preheat the oven to 350 degrees.",
            "Spread the olive oil around a glass baking dish.",
            "Add the salmon, garlic, and pine nuts to the dish.",
            "Bake for 15 minutes.",
            "Add the yellow squash and put back in the oven for 30 mins.",
            "Remove from oven and let cool for 15 minutes. Add the lettuce and serve."
        ]
    },
    {
        "name": "Fish Tacos",
        "ingredients": [
            { "name": "Whitefish", "amount": 1, "measurement": "lb" },
            { "name": "Cheese", "amount": 1, "measurement": "cup" },
            { "name": "Iceberg Lettuce", "amount": 2, "measurement": "cups" },
            { "name": "Tomatoes", "amount": 2, "measurement": "large"},
            { "name": "Tortillas", "amount": 3, "measurement": "med" }
        ],
        "steps": [
            "Cook the fish on the grill until hot.",
            "Place the fish on the 3 tortillas.",
            "Top them with lettuce, tomatoes, and cheese."
        ]
    }
]

我们还需要使用ReactDOM来渲染Menu组件。通过定义index.js做为这个项目的主文件,来负责渲染DOM。

import React from "react";
import { render } from "react-dom";
import Menu from './components/Menu';
import data from "../data/recipes.json";

render(
    <Menu recipes={data} />,
    document.getElementById("root")
);
  • 构建代码

我们把代码分成了不同的模块和文件,接下来要创建一个构建过程。再把一切都汇总到一个文件中。webpack是一个流行的构建工具。在使用之前需要先进行安装。

npm install --save-dev webpack webpack-cli

webpack默认的配置文件名为webpack.config.js,我们在配置文件中进行如下配置。

var path = require("path");

module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.json(__dirname, "dist", "assets"),
        filename: "bundle.js"
    }
};

首先我们告诉webpack,客户端的入口文件为./src/index.js。webpack将根据这个文件中的import语句自动构建依赖图。然后,指明我们想打包后的JavaScript输出到./dist/bundle.js文件中。

在我们正式打包之前,需要在借助Babel,来帮助我们将React JSX编译成JavaScript引擎能解析的React组件。同样也需要先安装一下Babel

npm install babel-loader @babel/core --save-dev

接下来,我们要设置webpack指令的一些loader,以便webpack在打包时可以使用babel先进行编译。

var path = require("path");

module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.join(__dirname, "dist", "assets"),
        filename: "bundle.js"
    },
    module: {
        rules: [{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}]
    }
};

现在,我们要指定运行Babel的预设(preset)。Babel通过预设设置执行什么转换操作。先进行类库安装:

npm install @babel/preset-env @babel/preset-react --save-dev

然后,在项目的根文件夹中新建一个文件,命名为.babelrc,并添加如下内容:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

至此,一个React应用的项目便创建好了。下面我们来运行webpack,

npx webpack --mode development

webpack将开始构建,如果构建成功,将会在dist文件夹中生成相关文件。

你还可以再package.json文件中添加一个npm脚本,创建一个快捷命令:

  "scripts": {
    "build": "webpack --mode production"
  },

这样就可以运行快捷命令生成构建包了。

npm run build

最后,我们再创建一个index.html作为页面启动文件,用于加载打包好的React代码。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>React Recipes App</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="./assets/bundle.js"></script>
    </body>
</html>

全部评论: 0

    我有话说: