要先保证Node >= 8.10 和 npm >= 5.6
- 安装脚手架
npm install -g create-react-app
- 创建项目
npx create-react-app my-app
cd my-app
npm start
注意
第一行的npx
不是拼写错误 —— 它是 npm 5.2+ 附带的 package 运行工具。
-
JSX
js的扩展
const text = <p>hello</p>
-
{表达式}
{/* 注释 */}
{ 函数/变量 }
{ jsx表达式 }
<img src={imp_path} style={{width:'100px}}>//{}中也可以是对象
-
组件
【注意】:组件首字母必须大写
-
新增组件文件
-
写组件
import React from 'react'
//组件有两种写法,1函数写法,2类写法
//props为传递的属性值,只读,单向
//函数类型的组件
export function Welcome1(props){
return(
<div>
welcome1,{props.name}
</div>)
}
//基于类的组件
export class Welcome2 extends React.Component{
render(props){
return <div>welcome2,{this.props.name}</div>//注意需要加上this
}
}
- 使用组件
import { Welcome1, Welcome2 } from './components/CompType';
<Welcome1 name="xyl"></Welcome1>//=>welcome1,xyl
<Welcome2 name="lgs"></Welcome2>
属性 | 作用 | 其他 |
---|---|---|
state | 状态 |
state使用注意事项
- 直接对state赋值无效//【然而我自己测试是有效的?】
- 批量执行
this.setState({
counter:this.state.counter+1
})
this.setState({
counter:this.state.counter+3
})
以上的写法只会执行最后一次的操作,若要多次操作需要用以下的写法:
this.setState((pre)=>{
return {
counter:pre.counter+1
}
})
this.setState((pre)=>{
return {
counter:pre.counter+1
}
})
state一般放在构造器当中
//状态初始化一般放在构造器当中
constructor(props){
super(props)
this.state={
goods:[
{id:1,name:'lululu'},
{id:2,name:'hanhan'}
]
}
}
钩子函数 | 作用 | 其他 |
---|---|---|
componentDidMount | 挂载 | |
componentWillUnmount | 卸载 | 清楚定时器等 |
条件渲染和循环
if,&&
map
如何双向绑定
react没有双向绑定,需手动绑定
<input type="input" value={this.state.input1} onChange={this.textChange}/>
注意onChange,on后面的C是大写的,且函数名后不要加()
textChange = (e)=>{//e为事件,最好用箭头函数,否则需注意this指向
this.setState({input1:e.target.value})
}
点击事件
state结构
this.state={
goods:[
{id:1,name:'lululu'},
{id:2,name:'hanhan'}
],
input1:''
}
不需要传参的点击事件
<button onClick={this.addGoods}>按钮</button>
需要传参的点击事件
//v=xxx
<button onClick={()=>{this.addToCart(v)}}></button>
addGoods = ()=>{
this.setState((pre)=>{//不要直接push,而是返回一个全新的数组
return {
goods:[
...pre.goods,
{id:pre.goods.length+1,name:pre.input1}
]
}
})
}
组件间的通信
与vue的不同在于,react的数据是单向的
子组件无状态
子组件不去做操作,都交给父组件操作
状态管理redux
生命周期
16.3之前的生命周期
16.4
稍后补充
使用ant_design
安装
npm i antd --save
组件中使用
import Button from 'antd/lib/button'
import 'antd/dist/antd.css'//引入整个css
按需加载
- 需要先安装几个插件
npm i react-app-rewired@2.0.2-next.0 babel-plugin-import --save
-
在根目录创建config-overrides.js文件
- config-overrides.js文件
const { injectBabelPlugin} = require("react-app-rewired")
module.exports = function override(config, env) {
config = injectBabelPlugin(
["import", { libraryName: "antd", libraryDirectory: "es", style: "css"}],
config
);
return config;
};
4.在package.json中把react-script改为react-app-rewired
- 引入方式也要有所改变
// import Button from 'antd/lib/button'
// import 'antd/dist/antd.css'//引入整个css
import {Button} from 'antd'
PureComponent
组件不继承自Component而是PureComponent
会进行浅比较
需注意传值的时候是只能有一层
也可以用 React.memo()
const Comment=React.memo( function(props){
return (
<div>
<div>{props.data.body}</div>
<div> --- {props.data.author}</div>
<hr/>
</div>
)
})
高阶组件
是一个函数
接受一个组件
加工返回新组件
强化组件的能力
网友评论