React 入门教程笔记

简介: React 入门教程笔记

安装 React

1、下载


wget https://cdn.staticfile.org/react/16.4.0/umd/react.development.js \
https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js \
https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js

react.min.js - React 的核心库

react-dom.min.js - 提供与 DOM 相关的功能

babel.min.js - Babel 可以将 ES6 代码转为 ES5 代码

Babel 内嵌了对 JSX 的支持


如果我们需要使用 JSX,则 <script> 标签的 type 属性需要设置为 text/babel


2、hello world


<script src="./react.development.js"></script>
<script src="./react-dom.development.js"></script>
<script src="./babel.min.js"></script>
<div id="app"></div>
<script type="text/babel">
  ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById("app"));
</script>

React 元素渲染

1、创建元素

元素是构成 React 应用的最小单位,用于描述屏幕上输出的内容


const element = <h1>Hello, world!</h1>;
// 将元素渲染到 DOM 中
ReactDOM.render(element, document.getElementById("app"));

2、更新元素

React 元素都是不可变的, 更新界面的唯一办法是创建一个新的元素


计时器示例


function tick() {
  const element = <h2>现在时刻:{new Date().toLocaleString()}</h2>;
  ReactDOM.render(element, document.getElementById("app"));
}
setInterval(tick, 1000);

2、封装成函数


function Clock(props) {
  return <h2>现在时刻:{props.date.toLocaleString()}</h2>;
}
function tick() {
  ReactDOM.render(<Clock date={new Date()} />, document.getElementById("app"));
}
setInterval(tick, 1000);

4、创建 React.Component 子类


class Clock extends React.Component {
  render() {
    return <h2>现在时刻:{this.props.date.toLocaleString()}</h2>;
  }
}
function tick() {
  ReactDOM.render(<Clock date={new Date()} />, document.getElementById("app"));
}
setInterval(tick, 1000);

JSX

1、使用 JavaScript 表达式


ReactDOM.render(<h1>{1 + 1}</h1>, document.getElementById("app"));

可以使用 conditional (三元运算) 表达式


2、样式

React 推荐使用 camelCase 语法设置内联样式


const style = {
  fontSize: 20,
  color: "#FF0000",
};
ReactDOM.render(
  <h1 style={style}>hello world!</h1>,
  document.getElementById("app")
);

3、注释


ReactDOM.render(
  <div>
    <h1>hello world!</h1>
    {/*注释*/}
  </div>,
  document.getElementById("app")
);

数组


数组会自动展开所有成员


var arr = [<h1>hello</h1>, <h1>world!</h1>];
ReactDOM.render(<div>{arr}</div>, document.getElementById("app"));

组件

原生 HTML 元素名以小写字母开头,

自定义的 React 类名以大写字母开头


class 属性需要写成 className ,

for 属性需要写成 htmlFor


1、函数定义组件


function MyComponent(props) {
  return <h1>{props.name}</h1>;
}
ReactDOM.render(<MyComponent name="Tom" />, document.getElementById("app"));

2、ES6 class 定义组件


class MyComponent extends React.Component {
  render() {
    return <h1>{this.props.name}</h1>;
  }
}
ReactDOM.render(<MyComponent name="Tom" />, document.getElementById("app"));

3、复合组件


function Name(props) {
  return <h1>名称:{props.name}</h1>;
}
function Url(props) {
  return <h1>网址:{props.url}</h1>;
}
function App() {
  return (
    <div>
      <Name name="百度" />
      <Url url="http://www.baidu.com" />
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("app"));

State(状态)

计时器每秒更新一次


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }
  // 挂载
  componentDidMount() {
    this.timerID = setInterval(() => {
      this.tick();
    }, 1000);
  }
  // 卸载
  componentWillUnMount() {
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({
      date: new Date(),
    });
  }
  render() {
    return <h1>{this.state.date.toLocaleString()}</h1>;
  }
}
ReactDOM.render(<MyComponent />, document.getElementById("app"));

Props

props 不可变, 用来传递数据


state 用来更新和修改数据


function Name(props) {
  return <h1>{props.name}</h1>;
}
ReactDOM.render(<Name name="Tom" />, document.getElementById("app"));

事件处理

事件绑定属性的命名采用驼峰式写法


function Link() {
  function handleClick() {
    console.log("按钮被点击了");
  }
  return <button onClick={handleClick}>按钮</button>;
}
ReactDOM.render(<Link />, document.getElementById("app"));

按钮点击开启和关闭


class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isToggleOn: true,
    };
  }
  handleClick(e) {
    this.setState((prevState) => ({
      isToggleOn: !prevState.isToggleOn,
    }));
  }
  render() {
    return (
      <button onClick={(e) => this.handleClick(e)}>
        {this.state.isToggleOn ? "开启" : "关闭"}
      </button>
    );
  }
}
ReactDOM.render(<Toggle />, document.getElementById("app"));

条件渲染

function User(props) {
  return <h1>User</h1>;
}
function Guest(props) {
  return <h1>Guest</h1>;
}
function App(props) {
  if (props.role == "user") {
    return <User />;
  } else {
    return <Guest />;
  }
}
ReactDOM.render(<App role="user" />, document.getElementById("app"));

列表 & Keys

每个列表元素需要分配一个兄弟元素之间的唯一 key


function App(props) {
  const numbers = [1, 2, 3];
  const items = numbers.map((item, index) => {
    return <li key={index}>{item}</li>;
  });
  return items;
}
ReactDOM.render(<App />, document.getElementById("app"));

组件 API

// 合并状态
setState(object nextState[, function callback])
// 替换状态
replaceState(object nextState[, function callback])
// 合并属性
setProps(object nextProps[, function callback])
// 替换属性
replaceProps(object nextProps[, function callback])
// 强制更新
forceUpdate([function callback])
// 获取DOM节点
DOMElement findDOMNode()
// 组件挂载状态
bool isMounted()

点击计数示例


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState((state) => {
      return { count: state.count + 1 };
    });
  }
  render() {
    return <h1 onClick={this.handleClick}>点击计数:{this.state.count}</h1>;
  }
}
ReactDOM.render(<App />, document.getElementById("app"));

组件生命周期

三个状态


Mounting:已插入真实 DOM

Updating:正在被重新渲染

Unmounting:已移出真实 DOM

生命周期的方法


componentWillMount 在渲染前调用

componentDidMount 在第一次渲染后调用

componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用

shouldComponentUpdate 在组件接收到新的 props 或者 state 时被调用

componentWillUpdate 在组件接收到新的 props 或者 state 但还没有 render 时被调用

componentDidUpdate 在组件完成更新后立即调用

componentWillUnmount 在组件从 DOM 中移除之前立刻被调用

AJAX

服务端 server.js


cnpm i express cors
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use("/", function (req, res) {
  return res.send({ data: { name: "Tom" } });
});
app.listen(8080, function () {
  console.log("listening: http://127.0.0.1:8080");
});

下载 axios 并引入

wget https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    };
  }
  componentDidMount() {
    axios.get("http://127.0.0.1:8080/").then((res) => {
      this.setState({
        name: res.data.data.name,
      });
    });
  }
  render() {
    return <h1>{this.state.name}</h1>;
  }
}
ReactDOM.render(<App />, document.getElementById("app"));

表单与事件

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({ value: event.target.value });
  }
  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        ></input>
        <h2>{this.state.value}</h2>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("app"));

Refs


         


ReactDOM.render(<App />, document.getElementById("app"));

相关文章
|
19天前
|
人工智能 缓存 前端开发
DeepSeek Harness 首发实测 + 入门教程,夯爆了!梁神我错了
DeepSeek Harness + DeepSeek V4 Pro 项目实战保姆级教程!手把手带你从零安装开源 AI 编程工具,开发架构图、知识讲解网站、3D 网页游戏、全栈 AI 应用 4 个项目,覆盖运行模式选择、插件安装与开发,看看能不能对标 Claude。
13115 84
DeepSeek Harness 首发实测 + 入门教程,夯爆了!梁神我错了
|
7天前
|
人工智能 自然语言处理 安全
阿里云千问办公、Qoder Teams、Qoder CN区别与选择指南:模型能力、适用场景与最新活动参考
本文聚焦阿里云2026年推出的三款自研AI办公产品,清晰拆解千问办公、Qoder Teams、Qoder CN的差异化定位与能力边界:千问办公主打职场全场景提效,支持自然语言指令一键完成PPT生成、数据分析等高频办公任务;Qoder Teams面向程序员团队,深度整合AI代码生成、团队协同与企业知识库能力;Qoder CN则专为金融、政务等强合规场景打造,实现数据不出境与VPC私有化部署。文章同步给出分场景选型指南与最新活动定价,帮助不同类型的企业按需组合产品,实现业务岗、研发岗与强合规场景的AI能力全覆盖。
阿里云千问办公、Qoder Teams、Qoder CN区别与选择指南:模型能力、适用场景与最新活动参考
|
2天前
|
缓存 人工智能 API
阿里云Qwen3.8‑Flash完整能力解析:模型特性、API调用实操与计费规则深度拆解
在AI应用快速落地的当下,开发者与企业选型大模型API,不再只单纯关注评测榜单分数,推理速度、上下文长度、多模态能力、工具调用稳定性以及实际调用成本,共同决定项目能否平稳上线。Qwen3.8‑Flash作为新一代多模态混合专家模型,主打高性能推理与低成本开销,面向编程开发、智能Agent工作流、超长文档解析、图文混合理解等高频场景,提供托管API服务,权重同时开放可供本地部署,兼容主流接口协议,能够无缝接入各类开发工具链。很多开发者在接入过程中,容易混淆普通按量Token计费、缓存计费、各类订阅计划之间的差异,造成实际账单超出预估。本文从模型底层架构、核心功能能力、适用场景、API调用实操、完
695 0
|
12天前
|
Web App开发 人工智能 API
16 个超火的 DeepSeek Harness 插件,大肥鱼已经落后 N 个版本了。。。
DeepSeek Harness 精选插件推荐合集,从图片识别、浏览器操控、多 Agent 协作到手机远程控制,一口气带你看完 DSH 社区热门的十几个插件,覆盖技能扩展、UI 界面增强、整活玩法三大类,让你的鲸鱼变得更强。
1736 4
|
13天前
|
人工智能 Java BI
【AI】DeepSeek Harness 安装、运行、管理插件
本文介绍了如何运行DeepSeek开源的Agent框架DeepSeek Harness(dsh)。主要内容包括:使用nvm安装适配的Node版本;通过代理加速克隆GitHub源码;使用pnpm安装依赖并启动项目;配置DeepSeek API Token;安装扩展功能的插件。该框架自带Web界面,支持模型适配、文件编辑等插件化功能
1918 1
|
人工智能 JavaScript 开发工具
DeepSeek Harness 本地安装与使用指南
DeepSeek Harness(DSH)是DeepSeek AI开源的Agent运行框架,支持本地文件操作、命令执行与工具调用。基于Cordis插件架构,具备高扩展性与强可控性,适合开发者搭建可控Agent环境或开展模型基准测试。当前为开发者预览版,需Node.js环境,推荐先用`npx @deepseek-ai/dsh web`快速体验。
5155 0
|
15天前
|
人工智能 JavaScript 测试技术
保姆级教程:DeepSeek Harness从安装到跑通测试,30分钟上手
DeepSeek Harness是DeepSeek开源的AI Agent运行时,主打“一行命令安装、5分钟跑通”。它让模型真正动手干活——读代码、跑测试、分析失败、生成修复方案。本文手把手教你30分钟从零上手,覆盖安装、配置、实测及避坑指南,助你快速掌握下一代AI编程范式。
|
8天前
|
人工智能 Linux iOS开发
Ollama使用教程:Ollama官网下载、Ollama本地部署大模型(2026最新)
Ollama 是一款免费开源的本地大模型运行工具,支持在 Windows/macOS/Linux 上离线运行 Qwen、DeepSeek、Llama 等主流开源模型,数据不出本机、隐私安全。提供 OpenAI 兼容 API,命令行一键拉取/运行/管理模型,无需联网,无调用限制,是开发者与 AI 爱好者部署本地 AI 助手的理想选择。(239 字)
|
14天前
|
人工智能 JavaScript 测试技术
从 0 到 1,DeepSeek Harness 保姆级安装与使用教程!
DeepSeek Harness是DeepSeek推出的开源Agent运行框架,秉持“一切皆插件”理念,支持模型、工具、技能、工作流等全模块自由替换与扩展。其核心Cordis内核实现动态插件管理,赋能Agent自进化。已成GitHub史上增速最快开源项目(15w+ Star),标志着国内大模型从拼价格转向重架构与生态的新拐点。
1350 6
从 0 到 1,DeepSeek Harness 保姆级安装与使用教程!