• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

react函数式组件传值:子传父

武飞扬头像
无翼之雀
帮助1

在用react进行函数式编程时,父组件可以通过props向子组件传值,那么子组件怎么向父组件传值呢?首先,父组件需要向子组件传递一个函数,然后,子组件通过props获取函数并附上参数,最后,父组件通过函数拿到子组件传递的值。

一、具体案例

父组件:home.tsx

  1.  
    import React, { useState } from 'react';
  2.  
    import Child from './component/child';
  3.  
    import './index.less';
  4.  
     
  5.  
    const Home: React.FC = () => {
  6.  
    const [parentCount, setParentCountt] = useState<number>(0);
  7.  
     
  8.  
    const getChildCount = (val: number) => {
  9.  
    setParentCountt(val);
  10.  
    };
  11.  
     
  12.  
    return (
  13.  
    <div className="home-wrap">
  14.  
    <p>我是父组件</p>
  15.  
    <p>子组件传过来的数字:{parentCount}</p>
  16.  
    <Child getCount={getChildCount} />
  17.  
    </div>
  18.  
    );
  19.  
    };
  20.  
     
  21.  
    export default Home;
学新通

子组件:child.tsx

  1.  
    import React, { useState } from 'react';
  2.  
     
  3.  
    type selfProps = {
  4.  
    getCount: Function;
  5.  
    };
  6.  
     
  7.  
    const Child: React.FC<selfProps> = (props) => {
  8.  
    const { getCount } = props;
  9.  
    const [count, setCount] = useState<number>(0);
  10.  
     
  11.  
    const addCount = (val: number) => {
  12.  
    setCount(val);
  13.  
    getCount(val);
  14.  
    };
  15.  
     
  16.  
    return (
  17.  
    <div className="child-wrap">
  18.  
    <p>子组件</p>
  19.  
    <p>数字:{count}</p>
  20.  
    <button onClick={() => addCount(count 1)}>数字递增</button>
  21.  
    </div>
  22.  
    );
  23.  
    };
  24.  
     
  25.  
    export default Child;
学新通

二、效果展示

学新通

【关联文章】

react函数式组件传值之父传子学新通https://blog.csdn.net/w544924116/article/details/119464737

感谢您读完本文!如果本文对您有帮助,请点个赞呗,您的点赞是对我最大的支持和认可!

我的公众号:大前端教程,欢迎关注,会定期更新前端知识,希望能帮到您。

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgafhbf
系列文章
更多 icon
同类精品
更多 icon
继续加载