1.创建:
在xx文件夹中建立项目(项目本身会重新在一个新的app-name中)
creat-react-app app-name
在src文件夹下创建组件文件夹,里面存放index.css和index.js,在index.js中定义组件
基本模板:
import React, { Component } from 'react'
import './index.css'
export default class Peiqi extends Component {
render(){
return (
<div>
xxx
<div>
)
}
}
2.props组件传参:
父组件传子组件:
<Child a={number} b="string">
<Child {...state}>
子组件拿值:
const {a,b} = this.props
3.事件处理:
1.使用类似onClick的小驼峰命名的回调函数,
2.回调函数传参的方法,必须返回一个函数:
export default class Peiqi extends Component{
const {id} = this.props
showData = (id)=>{
return (event)=>{
let {target, value} = envent
console.log(id, target, event)
}
}
render(){
return (
<div>
<button onClick={this.showData(id)}>Button</button>
</div>
)
}
}
4.生命周期
1.render:初始化渲染或更新渲染调用
2.componentDidMount:开启监听, 发送ajax请求
3.componentWillUnmount:做一些收尾工作, 如: 清理定时器
5.jsx语法规范:
1.标签中混入JS表达式时要用{}, 包括指定标签的回调函数和Js变量
2.样式的类名指定不要用class,要用className。
3.内联样式,要用style={{key:value}}的形式去写。
4.组件名称必须大写,否则视为html标签
6.state
初始化直接在类中定义state:
class MyComponent{
state = {'a':1, 'b':2}
render(){
return (
<div>
xxx
<div/>
)
}
}
读取state中的值 haha:
const {haha} = this.state
对state的值进行修改:
this.setState({isHot:!isHot})//改了哪个value就写对应的key
7.配置代理
在package.json中追加如下配置
"proxy":"http://localhost:5000"
8.消息订阅:
导入模块
import PubSub from 'pubsub-js'
发送消息:
PubSub.publish('msg-name',{isFirst:false,isLoading:true})
订阅消息
componentDidMount(){
this.token = PubSub.subscribe('msg-name',(_,stateObj)=>{
this.setState(stateObj)
})
}
componentWillUnmount(){
PubSub.unsubscribe(this.token)
}
9.axios使用
1.注意在get之后写的是poxy后面的内容
2.通过组件在componenetDidMount()中添加订阅 ==> 接受到消息,修改状态 ==> 在render中通过不同的状态返回不同的值实现loading
import axios from 'axios'
...
//发送请求前通知List更新状态
PubSub.publish('msg',{isFirst:false,isLoading:true})
axios.get(`/search/users2?q=${keyWord}`).then(
response => {
//请求成功后通知List更新状态
PubSub.publish('msg',{isLoading:false,users:response.data.items})
},
error => {
//请求失败后通知App更新状态
PubSub.publish('msg',{isLoading:false,err:error.message})
}
)