React 中級用法
阿新 • • 發佈:2019-01-25
React 前言
瞭解React的初級用法,就有必要知道React的一些中級用法,更加高效合理的處理一些事情和業務,讓開發變得更加簡單。
React 反向解析
- 元件CommonButton
- 元件命名首字母要大寫,若小寫會被認為html標籤
- 元件引用
js
<CommonButton size="large" isEnable={false}>
- 元件解析
js
React.createElement(
CommonButton,
{size: 'large', isEnable:false},
null
)
- JSX是React.createElement(component, props, …children)的語法糖
React refs用法
React PureComponent用法
當我們的元件沒有發生變化的時候如何避免重新被渲染,使用PureComponent來實現。
React.Component
定義元件
class CommonButton extends React.Component{ constructor(props) { super(props); this.state = {isEnable:true}; } //控制時候更新 shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.isEnable !== nextState.isEnable) { return true; } return false; } render() { return ( <button color={this.props.color} disabled={this.state.isEnable} onClick={()=>{this.setState({isEnable:!this.state.isEnable})}} > click </button> ); } }
React.PureComponent
定義元件
class CommonButton extends React.PureComponent{ constructor(props) { super(props); this.state = {isEnable:true}; } //PureComponent避免去控制shouldComponentUpdate函式是否渲染 render() { return ( <button
React 自動繫結
普通用法
class SayHello extends React.Component { constructor(props) { super(props); //繫結事件 this.handleClick = this.handleClick.bind(this); } handleClick() { alert("hello"); } render() { return ( <span onClick={this.handleClick}> say hello! </span> ); } }
箭頭函式
class SayHello extends React.Component { constructor(props) { super(props); } handleClick=()=> { alert("hello"); } render() { return ( <span onClick={this.handleClick}> say hello! </span> ); } }
- createReactClass() 建立元件和頁面是自動繫結的