• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
qiqi105
博客园    首页    新随笔    联系   管理    订阅  订阅

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;

 

posted @ 2018-06-21 15:43  qiqi105  阅读(1156)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3