import React from 'react'
import '../page1/header.css'
import { Table } from 'antd'
import Child from './child'//引入的子组件
export default class Header extends React.Component{
constructor(){
super()
}
}
onRef = (ref) => {//react新版本处理方式
this.child = ref
}
click = (e) => {
this.child.myName()
}
render(){
return (<div>
<Child onRef={this.onRef} />
<button onClick={this.click}>父组件调用子组件方法</button>
</div>
)
}
//子组件
import React from 'react'
export default class Header extends React.Component{
constructor(props){
super(props)
}
componentDidMount(){
this.props.onRef(this)
}
myName = () => alert('父组件调用子组件方法成功')
render(){
return (
<div className="header">
</div>
)
}
}
本文介绍了一个React应用中,父组件如何通过引用子组件实例来调用子组件的方法,实现跨组件的数据传递和交互。展示了使用React新版本的onRef属性进行组件间通信的具体实现。
1099

被折叠的 条评论
为什么被折叠?



