继承&组合
react
react 组件复用主要通过组合,继承也是可以的,只是组件之间关系的维护比较困难,官方推荐组合。
class Father extends React.Component {
constructor() {
super()
this.state = {
fatherName:"大头爸爸"
}
}
get fatherName(){
return this.state.fatherName
}
sing (){
return "唱了一首歌"
}
render() {
return (
<div style = {{color: "red"}}>
我是{this.state.fatherName}
</div>
)
}
}
// react的组件继承, 继承父组件的公有成员方法及属性
class Son extends Father {
constructor() {
super();
this.state ={
sonName: "小头儿子",
fatherName: super.fatherName,
grownUp: false
}
setTimeout(()=>{this.setState({grownUp:true})},3000)
}
render() {
const {sonName, fatherName, grownUp} = this.state;
return grownUp?(
<div>
我是:{sonName},我爸是:{fatherName},
表演才艺:{this.sing()}
</div>
):(<div>养成中...</div>)
}
}
function House(props){
const { area , price} = props;
return (
<div> 一栋楼{area}, 价值{price}</div>
)
}
// react的组件组合
function Home(props) {
const {others}=this.props;
return(<div>
<Father/>
<Son/>
<House area={"100平"} price={"100w"} />
{others isntanceof Array?others.map(people=>people):null}
</div>)
}
ReactDOM.render(
// 对比vue里面的this.$slot[name]和this.$slot.default
<Home />,
document.getElementById("app")
);
vue
vue组件的复用也可通过组合,这里不再复述。主要看看逻辑复用。vue提供了mixins,extends。
const mixin = {
created(){
console.log("mixin created", this.$data)
},
render(){
return(<div>mixin render</div>)
},
data(){
return {
content:[1],
mixinData:"mixinData"
}
},
methods:{
onClicked(){
console.log("mixin中事件执行函数被触发")
}
}
}
const Mixin = Vue.component("Mixin", mixin)
// 以下称Demo为被合并对象,mixin为合入对象。
// 会按一定的规则,合并选项对象, 状态合并,key无冲突合并,有冲突被合并的对象key优先。
// 生命周期,key无冲突合并,有冲突合入钩子执行内容,合入对象执行内容优先合入执行。
// render函数以被合并的对象为准。
// 事件处理函数key冲突,以被合并对象为准。
const Demo = Vue.component("Demo",{
// 混入
// mixins:[mixin],
// 扩展,不能理解为继承,内部还是以mixins一样的合并规则的对象合并实现的
extends: Mixin,
mounted() {
console.log("Demo, mounted")
},
render(){
return(<div onClick={()=>{ this.onClicked() }}>Demo render</div>)
},
created(){
console.log("demo created")
},
methods:{
onClicked(){
console.log("Demo中事件执行函数被触发")
}
},
data(){
return {
content:[],
inputValue:""
}
}
})