共计 3795 个字符,预计需要花费 10 分钟才能阅读完成。
博客原文
9102 年了,如果你还不会 react,希望本篇可以帮你快速了解 react.js 的基础知识。
创建项目
使用 create-react-app 工具快速创建 React SPA。
# 创建项目 | |
yarn create react-app my-app | |
cd my-app | |
# 开发模式下运行程序 | |
yarn start |
项目初始结构:
my-app/ | |
README.md | |
node_modules/ | |
package.json | |
public/ # 项目使用的公共文件 | |
index.html # 首页的模板文件 | |
favicon.ico # 项目的图标 | |
mainifest.json # 移动端配置文件 | |
src/ # 源代码 | |
App.css | |
App.js | |
App.test.js | |
index.css | |
index.js # 入口文件 | |
logo.svg |
Hello React
// src/index.js 入口文件 | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import App from './App'; | |
// 将根组件渲染到 id 为 root 的 dom 上 | |
ReactDOM.render(<App />, document.getElementById('root')); |
// src/app.js 根组件 | |
import React, {Component} from 'react'; | |
// 创建根组件 | |
class App extends Component {constructor(props) {super(props); | |
this.state = {msg: 'Hello React'} | |
} | |
render() { | |
// JSX 语法 | |
return ( | |
<div className="App"> | |
<h1>{this.state.msg}</h1> | |
</div> | |
); | |
} | |
} | |
export default App; |
最终这个根组件会在页面上显示出内容为 Hello React 的 h1 标题。
JSX
上例中在写根组件时,render 函数中提到了 JSX,简单的看,就是一个可以在 js 中写 html,简化了通过 React.createElement
创建 Dom,Babel 会将 JSX 转译。
JSX 中有以下几点需要注意:
-
<>
会当做 html 解析{}
会当做 js 解析; - class 替换为 className,for 替换为 htmlFor;
- 组件必须有一个最外层根元素包裹,若不想要根元素则可以使用
<Fragment>
,需要引入import {Fragment} from 'react'
;
写一个 ToDoList 应用
开始写之前先明确一下一个 ToDoList 的需求:
- 一个输入框输入要做的事;
- 一个添加按钮添加输入框中的事件到列表中;
- 一个展示当前已添加事件的列表;
- 点击列表中的事件表示已完成,则删除对应事件;
Todo 组件
先写一个名为 Todo 的组件,然后在 App 根组件中调用即可。
App.js 中调用 Todo 组件。
import React, {Component} from 'react'; | |
import Todo from './Todo' | |
class App extends Component {render() { | |
return (<Todo></Todo>); | |
} | |
} | |
export default App; |
调用自定义的组件时直接像原生 html 组件一样使用 <>
,区别是自定义组件需要以大写字母开头。
// Todo.js | |
import React, {Component, Fragment} from 'react'; | |
import TodoItem from './TodoItem'; | |
class Todo extends Component {constructor(props) {super(props); | |
this.state = { | |
inputVal: '早起', | |
list: ['吃早饭', '洗脸刷牙'] | |
}; | |
this.inputChange = this.inputChange.bind(this); | |
this.addItem = this.addItem.bind(this); | |
this.delItem = this.delItem.bind(this); | |
} | |
render() { | |
return ( | |
<Fragment> | |
<div> | |
<label htmlFor="todoIpt">todo: </label> | |
<input | |
id="todoIpt" | |
ref={iptRef => this.iptRef = iptRef} | |
value={this.state.inputVal} | |
onChange={this.inputChange} | |
/> | |
<button onClick={this.addItem}>+</button> | |
</div> | |
<ul> | |
{this.state.list.map((item, idx) => { | |
return ( | |
<TodoItem | |
key={idx+item} | |
idx={idx} | |
content={item} | |
delItem={this.delItem} | |
/> | |
) | |
}) | |
} | |
</ul> | |
</Fragment> | |
); | |
} | |
inputChange() { | |
this.setState({inputVal: this.iptRef.value}) | |
} | |
addItem() { | |
this.setState({list: [...this.state.list, this.state.inputVal] | |
}) | |
} | |
delItem(idx) { | |
const list = this.state.list; | |
list.splice(idx, 1); | |
this.setState({list}) | |
} | |
} | |
export default Todo; |
仍然引入 react 及 react.component 并使用 class 创建组件。
constructor 中通过 super 继承父组件传入的数据,通过 state 定义组件内部的数据。
render 函数中在 {} 中使用 js 给 html 动态绑定数据及事件,绑定的事件也定义在 class 中,需要通过 bind 修改 this 指向。
这里使用 ref 将输入框节点获取并保存在 this.iptRef
上,在 onchange 事件中修改其绑定的数据 inputVal。
修改数据时需要调用 setState 方法才能出发视图的更新。
ul 中直接使用 js 的 map 方法遍历 state.list
生成展示列表,列表中的每一项又单独抽出来作为一个新的子组件 TodoItem,并将子组件需要的数据 idx、content 及方法 delItem 传给他。
需要注意的时遍历生成的组件如果没有添加 key 属性则会报警告。
TodoItem 组件
import React, {Component} from 'react'; | |
import PropTypes from 'prop-types'; | |
class TodoItem extends Component {constructor(props) {super(props); | |
this.state = {}; | |
this.handleItemClick = this.handleItemClick.bind(this); | |
} | |
render() { | |
return (<li onClick={this.handleItemClick}> | |
{`${this.props.idx + 1}. ${this.props.content}`} | |
</li> | |
); | |
} | |
handleItemClick() {this.props.delItem && this.props.delItem(this.props.idx); | |
} | |
} | |
TodoItem.propTypes = { | |
idx: PropTypes.number.isRequired, | |
content: PropTypes.string.isRequired, | |
delItem: PropTypes.func | |
} | |
export default TodoItem; |
子组件直接通过 props 拿到父组件传递的数据包括方法。
子组件没法直接修改父组件传来的数据,因此需要调用父组件的方法来修改,比如这里的点击删除该项就是调用了父组件的 delItem 方法。
这里还引入了 prop-types
来帮助子组件进行传入数据的类型检查,还可以添加 isRequired 表明该数据是必须要传的,如果没有按照这个限制传给子组件数据则会有报错提示。
现在这个需求基本已经完成了。
生命周期
react 的每个组件都有一套生命周期函数,在组件开始渲染、更新到销毁的每个时间点都会执行对应的生命周期函数。
生命周期函数图谱
上面这个链接可以看到各种函数的执行顺序,最常用的 componentDidMount 就类似于 vue 的 mounted。
其中比较特殊的是 shouldComponentUpdate,它可以在组件更新之前进行拦截,return true
时才会执行 render 函数。
前面的 ToDoList 程序中,如果在子组件的 render 函数中增加一条 console.log 就会发现输入框的值每次变化都会触发所有组件的渲染,因此这里可以使用 shouldComponentUpdate 进行拦截。
TodoItem 组件中添加:
shouldComponentUpdate(nextProps, nextState) {nextProps, nextState); | |
return nextProps.content !== this.props.content; | |
} |
表明只有当 content 更新时才执行下一步 render 函数。
总结
到这基本上对 react 有了一个基本的了解了。