React 从入门到入门
组件的生命周期
- 给元素添加样式的时候需要两个大括号,例如:
// 外层大括号表示里面是 js 代码,里面的大括号表示内容是个对象
<h2 style={
{
opacity: opacity }}>{
this.props.msg}</h2>
- 经常在
componentDidMount()
生命周期中启动定时器 (挂载完毕的勾子函数) - 在
componentWillUnmount()
中获取停止定时器等操作 (移除组件的时候调用的方法)
注意:setInterval 和 setTimeout 里的 this 指向的都是 window
- 在节点上卸载组件方法:
// 卸载 .example 里面的组件
ReactDOM.unmountComponentAtNode(document.querySelector('.example'))
- 实例:让一句话每隔 2 秒重新设置一下透明度,并且有一个按钮可以直接清空这个组件
class Life extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
opacity: 1,
intervalId: 0
}
}
handleClick() {
// 删除整个组件
ReactDOM.unmountComponentAtNode(document.querySelector('.life'))
}
// 组件渲染到 DOM 中时的生命周期函数
componentDidMount() {
const intervalId = setInterval(function () {
let {
opacity } = this.state;
opacity -= 0.1;
if (opacity <= 0) {
opacity = 1;
}
// 这里我把 intervalId 放在了 state 里面,老师的操作是直接将 intervalId 放在了组件对象里 (this.intervalId)
this.setState({
opacity, intervalId });
}.bind(this), 200);
}
// 组件将要删除时候触发的生命周期函数
componentWillUnmount() {
// 清理定时器
clearInterval(this.state.intervalId)
}
render() {
let {
opacity } = this.state
return (<div>
// 外层大括号表示里面是 js 代码,里面的大括号表示内容是个对象
<h2 style={
{
opacity: opacity }}>{
this.props.msg}</h2>
<button onClick={
this.handleClick}></button>
</div>)
}
}
ReactDOM.render(<Life msg="React tql!" />, document.querySelector(".life"));
- 重要的勾子:
- render():初始化渲染或更新渲染调用
- componentDidMount():开启监听,发送 ajax 请求
- componentWillUnmount():做一些收尾工作,如:清理定时器
- componentWillReceiveProps():后面需要时讲
React 脚手架
-
在要安装的文件夹下执行
npm init react-app my-app
他会在该目录下安装 React app -
package.json 里面的 dependencies 是运行时依赖,devDependencies 是开发时依赖 (编译打包)
-
在 react 中,class 都要改变为 className
- 使用 create-react-app 创建应用 (两种方法安装的结果是一样的)
- 全局安装 react 脚手架 (create-react-app):
npm install -g create-react-app
- 创建项目:
create-react-app 项目名
- 进入这个项目:
cd 项目名
- 运行项目:
npm start
- 打开 localhost:3000 就能看到效果
- 写组件的时候最好把文件名写成 jsx 文件类型
- 组件的基本写法:
import React, {
Component } from 'react'
class App extends Component {
render() {
return (<div></div>)
}
}
// 暴露给外界
export default App;
- 或者暴露给外界也可以和上面的写到一起
export default class App extends Component {
render() {