Skip to content
{}

基础知识 - 组件通信

父子通信

传递数据(父传子) 与 传递方法(子传父)

父传子

父组件在组件上 传递数据可以了 利用属性props接收 类组件 接收用this.props 函数式组件 接收用 形参

子传父

父组件传递一个方法过去(回调函数) <div Fn={()=>{ }}><div/> 就说明 这个组件需要 子传父

子组件通过调用就可以传递数据了 类组件this.props.Fn() 函数式组件 形参调用

小Demo

import React, { Component } from 'react';
import ReactDom from 'react-dom';
<!-- 子组件 类组件-->
class App2 extends Component{
    render() {
        console.log(this.props)
        return (
            <div>
                <button onClick={() => {
                // 子传父 调用传递过来的方法 向父组件通信  利用了callback原理
                    this.props.Fn1('类组件')
                }}> 类组件点击 </button>
            </div>
        )
    }
}
<!-- 子组件 函数式组件-->
const App3 = (props) => {
    console.log(props)
    return (
        // 子传父 调用传递过来的方法 向父组件通信  利用了callback原理
        <div>
            <button onClick={() => {
                props.Fn2('函数式组件')
            }}>函数式组件点击</button>
        </div>
    )
}
<!-- 父组件 -->
class App extends Component {
    state = {
        show:true
    }
    App3Fn = (text) => {
        // 参数是 子组件传回来的数据
        console.log(text)
        this.setState({ show:!this.state.show})
    }
    render() {
        return (
            <div>
                <!-- 组件1 -->
                <App2 title='数据' Fn1={(text) => {
                    // 参数是 子组件传回来的数据
                    console.log(text)
                    this.setState({ show:!this.state.show})
                }}></App2>

                <!-- 组件2 -->
                <App3 title='数据2' Fn2={ this.App3Fn }></App3>

                {  this.state.show && '内容显示' }
        </div>
        )
    }
}
ReactDom.render(<App/>,document.getElementById('root'))

好好加油吧,少年!