React学习笔记20-父子通信(子传父)

发布时间 2023-11-08 09:59:49作者: SadicZhou

在React中子组件给父组件传参通过回调函数来进行。

父组件给子组件传递一个回调函数作为属性。

子组件在需要传递参数的地方调用父组件传递的回调函数即可。

import React, { Component } from 'react'
class Navbar extends Component {
    render() {
        return (
            <div style={{ backgroundColor: 'red' }}>
                <button onClick={
                    () => {
                        this.handlerClick()
                    }
                }>click</button>
                <span>navbar</span>
            </div>
        )
    }
    handlerClick() {
        this.props.event()//调用父组件传来啊的回调函数
    }
}
class Siderbar extends Component {
    render() {
        return (
            <div style={{ backgroundColor: "yellow", width: '200px' }}>
                <ul>
                    <li>11111</li>
                    <li>11111</li>
                    <li>11111</li>
                    <li>11111</li>
                    <li>11111</li>
                    <li>11111</li>
                    <li>11111</li>
                </ul>
            </div>
        )
    }
}
export default class App extends Component {
    state = {
        isShow: true
    }
    render() {
        return (
            <div>
                <Navbar event={() => {
                    console.log('event事件')
                    this.setState({
                        isShow: !this.state.isShow
                    })
                }}></Navbar>
                {this.state.isShow && <Siderbar></Siderbar>}
            </div>
        )
    }
}
/* 
        父传子:通过属性,
        子传父:通过回调函数
*/