一、函數組件
該函數在React中是一個有效的組件,可以接收唯一帶有數據的props(代表屬性)對象,並返回一個React元素。函數式組件要特別注意,組件名稱首字母一定要大寫。這種方式也成為無狀態組件。
特點有:
1.組件不會被實例化,整體渲染性能提升了。沒有實例化,就不需要分配多余的內存。
2.不能訪問this對象,像this.ref , this.state等不能訪問
3.組件無法訪問生命周期方法
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
二、React.createClass組件
ES5的原生JavaScript來實現的React組件,與函數式組件相比,React.Componen都是創建有狀態的組ss件,這些組件是要被實例化的。並且可以訪問組件的生命周期方法。
var InputControlES5 = React.createClass({ propTypes: {//定義傳入props中的屬性各種類型 initialValue: React.PropTypes.string }, defaultProps: { //組件默認的props對象 initialValue: '' }, // 設置 initial state getInitialState: function() {//組件相關的狀態對象 return { text: this.props.initialValue || 'placeholder' }; }, render: function() { return ( <div> Type something </div> ); } });
三、class組件
更加簡潔方便,this指向該組件,可以訪問到生命周期函數。數據可通過this.setState()方法進行修改。
class Welcome extends React.Component {
constructor(props){
super(props)//如果要使用props,這是必須的
}
render() { return <h1>Hello, {this.props.name}</h1>; } }
四、組件也可以進行組合
對有狀態組件也適用。
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } function App() { return ( <div> <Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" /> </div> ); } ReactDOM.render( <App />, document.getElementById('root') );