背景
- facebook
特点
- 声明式
- 组件化
高效
- 虚拟DOM,不总是直接操作dom
- diff算法,最小化重绘页面
issues
-
- 告诉babel去解析jsx语法
react库
- react.js 核心库
- babel.min.js 把jsx语法转为js语法
- react-dom.js 提供操作dom的react扩展库
步骤
- 创建虚拟dom,React.createElement(‘h1’, {id: “test”}, content)
- 渲染虚拟dom,ReactDOM.render(virtualDOM, containerDOM)
语法
- {}
- {{}} // 里面的代表是js对象,外边的代表里面要写js语法
模块与组件化
- 模块
- 复用js
- 一个js文件就是一个模块
- 组件
- 一个界面的不同部分
组件标签
- 首字母大小,大驼峰
定义组件
- 工厂函数,没有状态
- Person.propTypes
- React.PropTypes.string.isRequired
- Person.defaultProps
- this.props.propertyName
- class Test extends React.Component { render() { return } }
组件三大属性
- props
- state
- 初始化,constructor
- 读取,this.state
- 修改,this.setState
- refs
this
handleClick() {
}
render() {
<h1 onClick="this.handleClick.bind(this)"></h1>
}
PropTypes
refs
- <input type=‘text’ ref={inp => this.input} />
- inp 为当前dom元素
- this为当前组件对象
- 不要过度使用
组件化编写
- 拆分组件
- 实现UI组件
- 实现动态组件
- 初始化数据
- 绑定事件
- 后缀名可以写.jsx与.js,推荐前者
受控组件
非受控组件
生命周期
- constructor
- componentWillMount
- render
- componentDidMount
- componentWillUpdate
- render
- componentDidUpdate
- componentWillUnmount
移除组件
- ReactDOM.unmountComponentAtNode(document.getElementById(‘box’))
脚手架-create-react-app
- 就是去下载了一个已经存在的项目
- 包含了所有需要的配置
- 指定好了所有的依赖
- npm i create-react-app -g
- create-react-app project-name
package
- 开发时依赖,编译,打包需要,devDependencies
- 运行时依赖,dependencies
- 描述当前项目的信息
npm root -g // 查看全局安装的路径
请求-axios
- 在componentDidMount进行
请求-fetch
- 原生函数
- 老版本浏览器不支持
- 引入fetch.js兼容低版本浏览器
- 不再使用XmlHttpRequest对象
- 在IE8+以上的浏览器使用fetch是可行的
组件间通信-props
- props只能一层一层传递
- props可以传递一般数据和函数数据
组件间通信-subscribe-publish
- npm i pubsub-js
- 类似于vue的this.
e
m
i
t
和
t
h
i
s
.
emit和this.
emit和this.on
- pubSub.publish(‘search’, data)
- pubSub.subscribe(‘search’, (msg, data) => {})
- 适用于兄弟组件之间
路由-react-router
-
<BrowserRouter>
<App />
</BrowserRouter>
-
<HashRouter>
<App />
</HashRouter>
-
-
-
-
<NavLink className="" to="/home"></NavLink>
export default class MyNavLink extends Component {
render() {
return <NavLink {...this.props} activeClassName=""/>
}
}
-
<Switch>
<Route path="/home" component={HomeComponent} />
<Redirect to="/home" />
</Switch>
- history对象
- match对象
this.props.match.params
- withRouter函数
- npm i react-router-dom
- 通过js: this.props.history.push()、this.props.history.replace()、this.props.history.goBack() // 前进、this.props.history.goForward() // 后退
函数组件
- 单纯用来展示数据
- export default function ShowMessage(props) {return() {}}
UI
- material-ui(国外)
- antd-design(国内)
- https://mobile.ant.design/index-cn