前端學習-react組件
初始化生命周期
- defaultProps在初始化之前來預先定義默認屬性。例:SpecialView.defaultProps = { initialCount: 0 };
- constructor(props),初始化時設置this.state的值
- componentWillMount,render之前調用
- componentDidMount,render之后調用
- componentWillUnmount,界面上移除的時調用
更新組件
條件:state
- state表示組件內部狀態,只能在組件內部使用,state只應該用于存儲簡單的視圖狀態。
- 當sate改變時render會被調用,頁面就會刷新。
- state不能直接修改,應該使用 setState() 方法修改
方法:
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
其他
事件處理
同html事件屬性,推薦使用{::this.onClick}的方式綁定函數
DOM操作
- 組件加載之后通過 findDOMNode() 方法拿到組件對應的DOM元素
- 給標簽添加ref屬性,通過this.refs.name來獲取DOM元素
組合
組件內嵌套組件,循環插入組件,這些子組件都可以從props.children傳遞。
通信
- 父子組件通信通過props從父向子組件傳遞方法/數據
- 非父子組件通信通過全局事件 Pub/Sub 模式,在 componentDidMount 里面訂閱事件,在 componentWillUnmount 里面取消訂閱,當收到事件觸發的時候調用 setState 更新 UI