zoukankan      html  css  js  c++  java
  • vue 和react中子组件分别如何向父组件传值

    vue子组件和父组件双向传值:

    子:

    Vue.component("childComponent",{
    template:`<div><p @click='postData'>向父组件传值:点击我</p>{{result?'开':'关'}}<p @click='handleData'>子组件改变父组件的数值</p></div>`,
    props:{
    result:Boolean,
    changeData:Function
    },
    data(){
    return{
    message:'从子组件传过来的数据'
    }
    },
    methods:{
    postData(){
    this.$emit('receiveData',this.message)
    },
    handleData(){
    this.changeData()
    }

    }
    });

    父:

    const app = new Vue({
    el: '#app',
    router,
    data:{
    results:true,//开关状态数据
    ChildData:'',
    changedatas:'哈哈哈哈'
    },
    methods:{
    change(){
    this.results=!this.results;
    },
    FromChildData(data){
    this.ChildData = data
    },
    handleData(){
    this.changedatas +=2
    }
    },
    components: { App },
    template: `
    <div id="app">
    <p>changedatas:{{changedatas}}</p>
    <p>接收子组件的数据:{{ChildData}}</p>
    <childComponent :result="results"
    :change-data="handleData"
    @receiveData="FromChildData"></childComponent>
    <input type="button" value="change me 开 关" @click="change">
    </div>
    `
    })

    react子组件和父组件双向传值:

    父:

    import React, { Component } from 'react';
    import AppChild from './child.js'
    class AppParent extends Component {
    constructor(props){
    super(props);
    this.state = {
    parentData: '从父组件过来的数据',
    childData:'初始化数据'
    };
    }
    handleChildData = (childData) => {
    this.setState({
    childData:childData
    })
    };
    render() {
    let parentData = this.state.parentData;
    let childData = this.state.childData;
    return (
    <div className="parent">
    <p>接收来自子组件传来的数据:{childData}</p>
    <AppChild parentData={parentData} onChildDataChange={this.handleChildData}></AppChild>
    </div>
    );
    }
    }

    export default AppParent;

    子:

    import React, { Component } from 'react';
    class AppChild extends Component {
    constructor(props){
    super(props);
    }
    handleData = (e) =>{
    // 接受父组件传递过来的函数,调用并传值给父组件
    this.props.onChildDataChange(e.target.value)
    };
    render() {
    return (
    <div className="child">
    AppChild
    输入传入父组件的数据:<input type="text" value={this.props.childData} onChange={this.handleData}/>
    <p>{this.props.parentData}</p>
    </div>
    );
    }
    }

    export default AppChild;

  • 相关阅读:
    洛谷 1850 NOIP2016提高组 换教室
    2018牛客多校第三场 C.Shuffle Cards
    2018牛客多校第一场 B.Symmetric Matrix
    2018牛客多校第一场 A.Monotonic Matrix
    2018牛客多校第一场 D.Two Graphs
    2018宁夏邀请赛L Continuous Intervals
    2018宁夏邀请赛K Vertex Covers
    BZOJ
    HDU
    ACM International Collegiate Programming Contest, Egyptian Collegiate Programming Contest (ECPC 2015)
  • 原文地址:https://www.cnblogs.com/qiqi105/p/9209390.html
Copyright © 2011-2022 走看看