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用法
- refs使用场景
- 动画处理
- 焦点管理
- 三方插件
- 注意
- 不要去滥用refs
- render渲染之后才会拥有refs实例
- refs是访问内部组件的真实dom节点
- http://facebook.github.io/react/docs/more-about-refs.html
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 color={this.props.color} disabled={this.state.isEnable} onClick={()=>{this.setState({isEnable:!this.state.isEnable})}} > click </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() 创建组件和页面是自动绑定的
React 总结
最好的技术方案就是API文档,多去理解API文档有助于我们去更深入的理解或使用某一项技术。http://facebook.github.io/react/docs