React组件的构建:
React组件即为【 组件元素 】; 组件元素被描述为纯粹的JSON对象,意味着可以使用【 方法 】或者【 类 】来构建;
React组件基本上由3个部分组成---属性( props )、状态( state )、生命周期钩子函数;
React的所有组件都继承自顶层类 React.Component{};它的定义非常简洁,只是初始化
React.Component()方法,声明了 props、 state、 resf等,并在原型上(prototype)定义了 setState() 和
forceUpdate()。内部初始化的生命周期方法与 createClass 方式使用的是同一个方法创建的。
React组件的构建方法1:React.createClass()
const Button = React.createClass( {
getDefaultProps() {
return {
color: 'blue',
text: 'Confirm'
};
},
render(){
const { color, text } = this.props;
return (
<button className={ `btn btn-${color}`}>
<em>{ text }</em>
</button>
)
}
} );
/*
React.createClass()就是构建一个组件对象;当需要使用<Button />组件时;
会调用React.createElement()创建Button实例; 意味着只要调用<Button />
就会创建<Button />实例; 相当于只要调用 <Button /> 类时就会进行实例化
*/
React组件的构建方法2:React.Component{}
import React, { Component } from 'react';
class Button extends Component {
constructor( props ){
super( props );
}
static defaultProps = {
color: 'blue',
text: 'Confirm'
};
render() {
const { color, text } = this.props;
return (
<button className={ `btn btn-${color}`}>
<em>{ text }</em>
</button>
)
}
}
/*
此方法是从调用内部方法变成了用类来实现;与createClass()相同;
调用类实现的组件会创建实例对象
*/
React组件的构建方法3:(stateless function) 无状态函数构建的组件称为无状态组件
function Button({ color = 'blue', text = 'Confirm' } ){
return (
<button className={ `btn btn-${color}`}>
<em>{ text }</em>
</button>
)
};
/*
无状态组件只传入 props 和 context 两个参数;它不存在 state, 没有生命周期
的方法,也没有 render();但是 propsTypes 和 defaultProps 可以通过方法
设置静态属性来实现
*/
React组件的暴露的接口及入口:
暴露接口: export default class ComponentName extends React.Copmponent{};
组件入口: ReactDOM.render( <ComponentName />, document.getElementById( id ) );
组件也可以当成一个参数来传递
容器组件和傻瓜组件
一个组件基本上要完成以下两个功能:
· 根据当前 props 和 state ,渲染出用户界面
· 和 Redux Store 打交道, 读取 Store 的状态, 需要初始化组件的状态, 同时还要监听 Store 的
状态改变;当 Store 状态发生变化时, 需要更新组件状态,从而驱动组件重新渲染,;当需要
更新 Store 状态时,就要派发 action 对象
组件拆分
当 React 组件需要包办这两个任务时,会显得组件代码过于臃肿,那就需要把这个组件拆分成两个
组件。这样的关系里,两个组件是父子组件的关系。
负责和 Redux Store 打交道的组件,处于外层,被称为容器组件;只负责渲染界面的组件,处于内层
称为 展示组件
无状态组件
无状态组件没有状态、没有声明周期,只是简单的接受 props 渲染生成 DOM 结构,是一个纯粹为渲染而生的组件。由于无状态组件有简单、便捷、高效等诸多优点,所以尽量使用无状态组件
const HelloWorld = ( props ) => { return ( <div>{ hello world }</div> ) }