首页 > 语言 > JavaScript > 正文

React.js中常用的ES6写法总结(推荐)

2024-05-06 15:17:24
字体:
来源:转载
供稿:网友

一 模块

1 引入模块以便使用

用import实现:

import '模块文件地址'import 组件 from '模块文件地址'

2 导出模块

用export default实现:

export default class MyComponent extends Component{  ...}

引用:

import MyComponent from './MyComponent';

二 组件

1 定义组件

通过定义一个继承自React.Component的class来定义一个组件类:

class Photo extends React.Component {  render() {    ...  }}

2 定义组件方法

直接用名字(){},很像Java定义类方法的写法:

class Photo extends React.Component {  componentWillMount() {  }  render() {    return (      <Image source={this.props.source} />    );  }}

3 定义组件的属性类型和默认属性

统一使用static成员来实现:

class Video extends React.Component {  static defaultProps = {    autoPlay: false,    maxLoops: 10,  }; // 注意这里有分号  static propTypes = {    autoPlay: React.PropTypes.bool.isRequired,    maxLoops: React.PropTypes.number.isRequired,    posterFrameSrc: React.PropTypes.string.isRequired,    videoSrc: React.PropTypes.string.isRequired,  }; // 注意这里有分号  render() {    return (      <View />    );  } // 注意这里既没有分号也没有逗号}

注意: 对React而言,static成员在IE10及之前版本不能被继承,而在IE11和其它浏览器上可以,有时会带来一些问题。React Native则不用担心这个问题。

4 初始化STATE

在构造函数中初始化(这样可以根据需要做一些计算):

class Video extends React.Component {  constructor(props){    super(props);    this.state = {      loopsRemaining: this.props.maxLoops,    };  }}

5 把方法作为回调提供并使用

ES5下可以这么做:

//ES5var PostInfo = React.createClass({  handleOptionsButtonClick: function(e) {    // Here, 'this' refers to the component instance.    this.setState({showOptionsModal: true});  },  render: function(){    return (      <TouchableHighlight onPress={this.handleOptionsButtonClick}>        <Text>{this.props.label}</Text>      </TouchableHighlight>    )  },});

在ES5下,React.createClass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在认为这是不标准、不易理解的。

ES6下,需要通过bind来绑定this引用,或者使用箭头函数(它会绑定当前scope的this引用)来调用:

//ES6class PostInfo extends React.Component{  handleOptionsButtonClick(e){    this.setState({showOptionsModal: true});  }  render(){    return (      <TouchableHighlight         onPress={this.handleOptionsButtonClick.bind(this)}        onPress={e=>this.handleOptionsButtonClick(e)}        >        <Text>{this.props.label}</Text>      </TouchableHighlight>    )  },}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选