主題:React組件 繼承 自定義的 組件
一、需求說明
情況說明: 有A,B,C,D 四個組件,里面都有一些公用的邏輯,比如 設置數據,獲取數據,有某些公用的的屬性,不想在 每一個 組件里面寫這些屬性,怎么辦? 【和 面向對象的語言,C#,Java 的基類 思想是 一樣的】
如果公用的東西,是一些方法,可以 使用 React 的 Mixins(ES5) ,高階組件(ES6)【高階函數不太了解,如何使用,去找下資料 】
但是如果有公用的屬性,那么就有點 力不從心了
在想,React 中,是否可用繼承 自定義的組件?
經過一番查找資料,發現,React 是可以 繼承 自己定義的組件的
二、解決方案
實現的步驟很簡單,只需要 把
classWin extends React.Component
替換成
classWin extends BaseWin
1. 例子代碼
importReact from 'react'
/**
* 所有彈框的基類
*/
classBaseWin extends React.Component{
constructor(props){
super(props);
this.name ='zhongxia';
this.state ={};
}
common(){
alert('this is a common function!')
}
}
exportdefaultBaseWin;
importReact from 'react'
importBaseWin from './baseWindow'
classWin extends BaseWin{
constructor(props){
super(props);
this.state ={
...this.props
};
console.log(this.name);
this.common();
}
getData(){
returnthis.state;
}
render(){
this.state.node.model.set({name:'zhongxia', age:17})
return(
<div className="pop-dialog">
<h2>彈框1</h2>
<form>
<label htmlFor="">用戶名:</label><input value={this.state.name} type="text"/>
<label htmlFor="">密碼:</label><input type="password" value={this.state.password}/>
</form>
</div>
);
}
}
exportdefaultWin;
2. 實例化 React 組件的順序 和效果圖
實例化子類組件 ==》 構造函數里面 super(prop)的時候去實例化 父類組件 ==》 父類組件實例化結束 ==》 子類組件實例化結束
運行的效果圖:
1. 子類構造函數
2. super(props) 實例化父類
3. 子類構造函數結束,已經可以拿到父類的屬性和方法
4. 子類實例開始渲染頁面
您可能還感興趣
1. 【GITHUB】前端技術文章匯總