React创建组件的三种方式

1.函数创建的组件,这种组件被称为无状态组件:具有以下主要特点

a: 组件不会被实例化,整体渲染性能得到提升

b: 组件不能访问this对象

c: 组件无法访问生命周期的方法

d: 无状态组件只能访问输入的props,同样的props会得到同样的渲染结果,不会有副作用

如: function Upfile(props){

 return  <h1>{ props.title }<h1>}

ReactDOM.render(<Upfile name="文件名字" />,目标元素)

 

2.采用`React.createClass Es5写法: 形式

var Upfile = React.createClass({

propTypes: {//定义传入props中的属性各种类型 initialValue: React.PropTypes.string },

 

 

defaultProps: {

//组件默认的props对象

initialValue: '' },

 

 

// 设置 initial state

getInitialState: function() {

//组件相关的状态对象

return { text: this.props.initialValue || 'placeholder' };

},

3.React.Component是 Es6形式

class InputControlES6 extends React.Component {

 

 

constructor(props) { super(props);

 

 

// 设置 initial state this.state = { text: props.initialValue || 'placeholder' };

 

// ES6 类中函数必须手动绑定

this.handleChange = this.handleChange.bind(this);

}

总结: 2 3 方法相同,不同Es环境下的写法,可以访问this,周期函数

posted @ 2022-03-30 12:31  天堂花草  阅读(245)  评论(0)    收藏  举报