美文网首页
组件通信

组件通信

作者: 不信不信不相信 | 来源:发表于2018-10-29 12:27 被阅读0次

组件通信分为几种:

    父组件给子组件通信

    子组件给父组件通信

    兄弟组件通信

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>

        )

    }

相关文章

  • vue中的组件通信

    一、组件通信(组件传值) 1.1父子组件通信 1.2子父组件通信 1.3非父子组件通信(兄弟组件通信)

  • 组件通信

    组件通信分为几种: 父组件给子组件通信 子组件给父组件通信 兄弟组件通信 1.父组件给子组件通信 法一...

  • 组件通信

    组件关系 组件关系可以分为父子组件通信、兄弟组件通信、跨级组件通信。 父子组件通信 1. 子组件使用 $emit(...

  • react之组件通信

    需要组件之进行通信的几种情况: 父组件向子组件通信 子组件向父组件通信 跨级组件通信 没有嵌套关系组件之间的通信 ...

  • React组件通信的几种方式

    需要组件之进行通信的几种情况 父组件向子组件通信 子组件向父组件通信 跨级组件通信 没有嵌套关系组件之间的通信 1...

  • React中组件通信的几种方式

    需要组件之进行通信的几种情况 父组件向子组件通信 子组件向父组件通信 跨级组件通信 没有嵌套关系组件之间的通信 1...

  • React中组件通信

    需要组件之进行通信的几种情况 父组件向子组件通信 子组件向父组件通信 跨级组件通信 没有嵌套关系组件之间的通信 1...

  • 第七章 可复用性的组件详解(中)

    7.7 组件通信 组件关系可分为父子组件通信、兄弟组件通信、跨级组件通信 7.7.1 自定义事件—子组件给父组件传...

  • vue 组件通信方式 ,父子、隔代、兄弟 三类通信,六种方法

    Vue 组件间通信只要指以下 3 类通信:父子组件通信、隔代组件通信、兄弟组件通信,下面分别介绍每种通信方式且会说...

  • react 跨级组件通信

    跨级组件通信所谓跨级组件通信,就是父组件向子组件的子组件通信,向更深层的子组件通信。跨级组件通信可以采用下面两种方...

网友评论

      本文标题:组件通信

      本文链接:https://www.haomeiwen.com/subject/sizvtqtx.html