父组件
import React from 'react'
import Header from './Header'
import Footer from './Footer'
class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
title: '父组件'
}
}
run = () => {
alert('我是父组件的run方法')
}
getData = () => {
alert(this.state.title)
}
// 获取子组件传过来的数据
getChildData = (result) => {
alert(result)
this.setState({
title: result
})
}
// 父组件自动调动子组件的方法
getFooter = () => {
alert(this.refs.footer.state.title)
this.refs.footer.run()
}
render () {
return (
<div>
{/* 父子组件传值:
父组件给子组件传值
1.在调用子组件的时候定义一个属性 <Header msg='首页'></Header>
2.子组件里面 this.props.msg
说明:父组件不仅可以给子组件传值,还可以给子组件传方法,以及把整个父组件传给子组件。
父组件主动获取子组件的数据
1、调用子组件的时候指定ref的值 <Header ref='header'></Header>
2、通过this.refs.header 获取整个子组件实例 dom加载完成后获取*/}
{/* 将title传递给子组建 */}
{/* 传递父组件的方法 */}
{/* 将整个父组件传递过去 */}
<Header title={this.state.title} run={this.run} father={this}></Header>
{this.state.title}
<hr />
<button onClick={this.getFooter}>获取整个子组件</button>
<Footer ref='footer'></Footer>
</div>
)
}
}
export default Father
子组件Header
import React from 'react'
class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
title: '头部组件'
}
}
getFather = () => {
this.props.father.getData()
}
render () {
return (
<div>
{/* 父子组件传值:
父组件给子组件传值
1.在调用子组件的时候定义一个属性 <Header msg='首页'></Header>
2.子组件里面 this.props.msg
说明:父组件不仅可以给子组件传值,还可以给子组件传方法,以及把整个父组件传给子组件。
父组件主动获取子组件的数据
1、调用子组件的时候指定ref的值 <Header ref='header'></Header>
2、通过this.refs.header 获取整个子组件实例 */}
{/* /接受父组件传过来的title值 */}
<h2>{this.props.title}</h2>
<button onClick={this.props.run}>调用父组件的run方法</button>
<button onClick={this.props.father.getData}>获取整个父组件</button>
<button onClick={this.getFather}>执行父组件的方法</button>
<button onClick={this.props.father.getChildData.bind(this, '我是子组件传递过来的值')}>子组件传递父组件的值</button>
{this.state.title}
</div>
)
}
}
export default Header
子组件Footer
import React from 'react'
class Footer extends React.Component {
constructor(props) {
super(props)
this.state = {
title: '底部组件'
}
}
getFather = () => {
this.props.father.getData()
}
run = () => {
alert('我是底部组件的run方法')
}
render () {
return (
<div>
{this.state.title}
</div>
)
}
}
export default Footer