react 做个简单的组件通讯 子---父

72 阅读1分钟

思路 :

利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数

步骤:

1.父组件

1.定义一个回调函数f (将会用于接受数据) 2.将该函数f 作为属性的值,传递给子组件

2.子组件

1.通过 props 获取 f

2.调用f ,并传入将子组件的数据

父组件
import React, { Component }  from "react";
import ReactDOM  from "react-dom";
import Son from './Son'

export default class Parent extends Component{
state ={
    num : 1
}
f = (abc) => {
    console.log(abc)
}
render () {
    return (
        <div>
            <h2>父组件{this.state.num}</h2>
            <Son f={this.f} />
        </div>
    )
}
}

// 渲染
ReactDOM.render(<Parent />,document.getElementById('root'))

import React, { Component } from ‘react’

export default class Son extends Component {
hclick = () => {
this.props.f(100)
}
render () {
console.log(‘要接受的数据’, this.props)
return (
子组件
)}}