背景
- 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.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