react中子组件向父组件传值

1.子组件使用this.props.函数名来传值

import React, { Component } from "react";

export default class Son extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zitext: "我是子组件的008,我要传递给父组件"
    };
  }
  render() {
    return (
      <div>
        {/* fufun是子组件定义的方法,父组件中要用这个方法来接受数据,this.state.zitext就是数据*/}
        <button onClick={this.props.fufun.bind(this, this.state.ziText)}>
          点我进行数据的发送
        </button>
      </div>
    );
  }
}

2.父组件中要以子组件定义的方法名来定义一个方法,并接受数据

import React, { Component } from "react";
import Son from "./Son";
export default class Father extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "我是默认值"
    };
  }
  // text就是传递过来的数据
  dataFun = text => {
    console.log(text);
    // 将从子组件取过来的数据设置到当前页面上
    this.setState({ text });
  };
  render() {
    return (
      <div>
        我是父组件father--{this.state.text}
        {/*fufun是子组件定义的,fafaun是父组件定义的函数*/}
        <Son text="父组件的值001" fufun={this.dataFun} />
      </div>
    );
  }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值