首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >react父子传值

react父子传值

作者头像
hss
发布2022-02-25 19:41:14
发布2022-02-25 19:41:14
4730
举报
文章被收录于专栏:前端卡卡西前端卡卡西

父传子

类组件

代码语言:javascript
复制
import React, { Component } from 'react';


// 子组件
class ChildCpn extends Component {
  // 如果只是下面的形式,可以省略
  // constructor(props) {
  //   super(props);
  // }

  render() {
    const { name, age, height } = this.props;
    return (
      <h2>子组件展示数据: {name + " " + age + " " + height}</h2>
    )
  }
}

// 父组件
export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn name="hss" age="21" height="1.7" />
        <ChildCpn name="kobe" age="40" height="1.98" />
      </div>
    )
  }
}

函数组件

代码语言:javascript
复制
import React, { Component } from 'react';

// 子组件
function ChildCpn(props) {
  const { name, age, height } = props;

  return (
    <h2>{name + age + height}</h2>
  )
}

// 父组件
export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn name="hss" age="21" height="1.7" />
        <ChildCpn name="kobe" age="40" height="1.98" />
      </div>
    )
  }
}

子传父

函数传递

代码语言:javascript
复制
import React, { Component } from 'react';

// 子组件
class CounterButton extends Component {
  render() {
    const { onClick } = this.props;
    return <button onClick={onClick}>+1</button>
  }
}

// 父组件
export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      counter: 0
    }
  }

  render() {
    return (
      <div>
        <h2>当前计数: {this.state.counter}</h2>
        <button onClick={e => this.increment()}>+</button>
        <CounterButton onClick={e => this.increment()} name="why" />
      </div>
    )
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1
    })
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/10/14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 父传子
    • 类组件
    • 函数组件
  • 子传父
    • 函数传递
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档