组件通信

组件通信分为几种:

    父组件给子组件通信

    子组件给父组件通信

    兄弟组件通信

1.父组件给子组件通信

法一:

子组件页面:

import React from 'react';

export default class Child extends React.Component{

    constructor(props) {

        super(props)

    }

    render() {

        return (

            <div>

                <h1>Hello,{this.props.name}</h1>

            </div>

        )

    }

}

父组件页面:

<Child name='lala'/>

法二:

子组件页面:

import React from 'react';

import PropTypes from 'prop-types';

export default function Child({ name }) {

    return <h1>Hello,{name}</h1>

}

Child.PropTypes = {

    name:PropTypes.string.isRequired,

}

父组件页面:

<Child name='lala'/>

2.子组件给父组件通信:

子组件:

import React from 'react';

export default class Child extends React.Component{

    constructor(props) {

        super(props)

    }

    render() {

        return (

            <div>

                哈哈哈哈,我是子组件

                <button onClick={this.props.hideComponent}>隐藏子组件</button>

            </div>

        )

    }

}

父组件:

import React from 'react';

import Child from './child';

export default class App extends React.Component{

    constructor() {

        super()

        this.state = {

            isShowChild:true

        }

    }

    showComponent = () => {

        this.setState({

            isShowChild: true

        })

    }

    hideComponent = () => {

        this.setState({

            isShowChild: false

        })

    }

    render() {

        return (

            <div>

                <button onClick={this.showComponent}>显示child组件</button>

                {

                    this.state.isShowChild ? <Child hideComponent= {this.hideComponent}/> : null

                }

            </div>

        )

    }

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容