美文网首页
2-2 子传父数据 demo

2-2 子传父数据 demo

作者: bestCindy | 来源:发表于2020-07-19 22:26 被阅读0次
import ReactDOM from 'react-dom';
import React from 'react';

//子传父
class ParentCom extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          childData : null
        }
    }

    render() {
        return (
            <div>
                <h1>子元素传递给父元素的数据:{ this.state.childData }</h1>
                <ChildCom setChildData = { this.setChildData } />
            </div>
        )
    }

    setChildData = (data) => {
        this.setState({
            childData: data
        })
    }
}

class ChildCom extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            msg: "Hello World!"
        }
    }

    render() {
        return(
            <div>
                <button onClick = { this.sendData }>传递 hello world 给父元素</button>
                <button onClick = { () => { this.props.setChildData("Hello") }}>传递 hello 给父元素 </button>
            </div>
        )
    }

    // 将子元素传递给父元素,实际就是调用父元素传递进来的父元素函数
    sendData = () => {
        this.props.setChildData(this.state.msg);
    }
}
ReactDOM.render(<ParentCom />, document.querySelector("#root"));

相关文章

  • 2-2 子传父数据 demo

  • react父子通讯

    父子通讯父传数据给子,子传数据给父 react组件class 组件名 extends React.Componen...

  • [JS][Vue]学习记录之子向父传值

    demo地址前面介绍了父组件向子组件传值,那么子组件如何向父组件传值呢?以前面的demo为例,假如header要向...

  • Vue 父组件向子组件传值

    Vue 父组件向子组件传值 demo代码 (vue.js ...

  • 02.1 - vue 组件间传参 props

    一、用法 父组件、子组件概念: 二、父组件传参给子组件 - props 1、传静态数据 1、父组件传参 2、子组...

  • 2019-01-18 Vue学习

    父组件传数据给子组件(props),子组件传给父组件($emit("触发大的事件”,传的数据)) 插槽(slot)...

  • Vue父子组件之间的通信

    父传子:通过在子组件标签中传值,子组件通过props进行接收。子传父:通过事件,$emit(父组件方法,数据),父...

  • vue单文件父子组件之间的通信

    主要笔记内容: 父组件向子组件传值; 子组件向父组件传值; 一、父组件向子组件传值: 步骤:1、父组件向下传递数据...

  • 浅谈Vue父子组件传值

    demo代码 看了vue文档后写了个小demo来验证,代码如下: 运行结果: 一、父组件向子组件传值(props传...

  • 父子组件传值

    父组件向子组件传值 1、props传递属性原则,是单向数据流,只允许父向子传值,不允许子操作父的数据。 2、子组件...

网友评论

      本文标题:2-2 子传父数据 demo

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