1. 组件定义
import React from 'react';
let TodoItem = React.createClass({
render(){
return <div>div>
}
})****
ES6 实现了 class. 于是, 出现了新的写法
import React from 'react';
class TodoItem extends React._Component_{
constructor(props){
super(props)
}
render(){
return
}
}
对比一下这两种写法的不同之处
1. propTypes 和 getDefaultProps
import React from 'react';
let TodoItem = React.createClass({
propTypes: { // as an object
name: React.PropTypes.string
},
getDefaultProps(){ // return a object
return {
name: ''
}
}
render(){
return <div>div>
}
})
import React form 'react';
class TodoItem extends React._Component_{
static propTypes = { // as static property
name: React.PropTypes.string
};
static defaultProps = { // as static property
name: ''
};
constructor(props){
super(props)
}
render(){
return
}
}
2. 初始状态
import React from 'react';
let TodoItem = React.createClass({
// return an object
getInitialState(){
return {
isEditing: false
}
}
render(){
return <div>div>
}
})
import React from 'react';
class TodoItem extends React._Component_{
constructor(props){
super(props);
this.state = { // define this.state in constructor
isEditing: false
}
}
render(){
return
}
}
3. this
import React from 'react';
let TodoItem = React.createClass({
handleClick(){
console.log(this); // React Component instance
},
render(){
return
}
})
import React from 'react';
class TodoItem extends React.Component{
constructor(props){
super(props);
}
handleClick(){
console.log(this); // null
}
handleFocus(){ // manually bind this
console.log(this); // React Component Instance
}
handleBlur: ()=>{ // use arrow function
console.log(this); // React Component Instance
}
render(){
return this.handleClick}
onFocus={this.handleFocus.bind(this)}
onBlur={this.handleBlur}/>
}
}
4.Mixin
import React from 'react';
let MyMixin = {
doSomething(){}
}
let TodoItem = React.createClass({
mixins: [MyMixin], // add mixin
render(){
return <div>div>
}
})
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于