6.vue和react一起学 (*^_^*)

11 篇文章 0 订阅

继承&组合

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:""
        }
    }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值