认识

简单使用

  1. 添加根容器 <div id="app">...</div>
  2. 引入 CDN 脚本
  3. 创建 React 组件
    1. React: 提供 React API(处理视图的 API 集合)
    2. React-DOM:从 render → 虚拟 DOM → 真实 DOM
    3. 继承 React.Component
    4. render 函数返回一个视图

CDN Links - 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>Learning React</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- 开发环境 -->
    <script
      crossorigin
      src="<https://unpkg.com/react@17/umd/react.development.js>"
    ></script>
    <script
      crossorigin
      src="<https://unpkg.com/react-dom@17/umd/react-dom.development.js>"
    ></script>
    <!-- 生产环境 -->
    <!-- <script
      crossorigin
      src="<https://unpkg.com/react@17/umd/react.production.min.js>"
    ></script>
    <script
      crossorigin
      src="<https://unpkg.com/react-dom@17/umd/react-dom.production.min.js>"
    ></script> -->
    <script src="./js/01简单使用.js"></script>
  </body>
</html>
const span = React.createElement(
  "span",
  {
    className: "text",
    key: 1,
  },
  "This is a span"
);
ReactDOM.render(
  React.createElement(
    "div",
    {
      className: "container",
    },
    [span]
  ),
  document.getElementById("app")
);

Untitled

使用 class 创建组件

class MyButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openStatus: false,
    };
  }
  render() {
    const oP = React.createElement(
      "p",
      {
        className: "text",
        key: 1,
      },
      this.state.openStatus ? "打开状态" : "关闭状态"
    );
    const oBtn = React.createElement(
      "button",
      {
        key: 2,
        onClick: () =>
          this.setState({
            openStatus: !this.state.openStatus,
          }),
      },
      this.state.openStatus ? "关闭" : "打开"
    );
    const oWrapper = React.createElement(
      "div",
      {
        className: "container",
      },
      [oP, oBtn]
    );
    return oWrapper;
  }
}

const span = React.createElement(
  "span",
  {
    className: "text",
    key: 1,
  },
  "This is a span"
);
ReactDOM.render(React.createElement(MyButton), document.getElementById("app"));

Untitled

Create a New React App

npx create-react-app my-react-app
cd my-react-app
npm start

函数组件写法