在使用模块化开发,经常会遇到组件之间的传值问题,这篇说一下react子组件如何向父组件传值,父组件如何获取子组件的数据和方法
父组件:
import React, { Component } from 'react';
import Header from './Header.js' //引入子组件
class Home extends Component{
constructor(props){
super(props)
this.state={
title:'首页'
}
}
getChildData=(res)=>{
alert(res)
this.setState({
msg:res
})
}
render(){
return(
<div>
<Header news={this}/> //这里给子组件定义一个news属性为this
</div>
)
}
}
export default Home
子组件添加一个按钮定义一个onClick事件this.props.news.getChildData就可以调用父组件的方法并使用bind绑定this和传递参数
<button onClick={this.props.news.getChildData.bind(this,'我是子组件的数据')}>子组件给父组件传值</button>
这里父组件中的getChildData方法就可以通过形参接收参数。
父组件主动获取子组件的数据及方法
1.调用子组件的时候指定一个ref值
2.通过this.refs.header 获取整个子组件实例 (注意要在dom加载完成之后获取)
ref的使用我这篇文章中有写,这里不再说明,传送门!