为了能到远方,脚下的每一步都不|

505donkey

园龄:6年3个月粉丝:6关注:0

2024-09-02 01:23阅读: 27评论: 0推荐: 0

【React】组件通信 - 父传子

组件通信

概念

  • 组件通信就是组件之间的数据传递,根据组件嵌套关系的不同,有不同的通信方法。

分类

  • 父子通信、兄弟通信、跨层通信

父传子

实现步骤

  • 父组件传递数据 - 在子组件标签上绑定属性
  • 子组件接收数据 - 子组件通过props参数接收数据

示例

  • function Son(props) {
    return <div>this is son, {props.name}</div>
    }
    
    function App() {
    const name = 'this is farther'
    return (
        <div>
        <Son name={name} />
        </div>
    );
    }
    ...
    

props参数

说明

  • props可以传递任意的数据:数字、布尔值、字符串、数组、对象、函数、JSX。
  • props是只读对象:子组件只能读取props中的数据,不能直接进行修改,父组件的数据只能由父组件修改。

示例

function Son(props) {
  return <div>this is son, {props.name}</div>
}

function App() {
  const name = 'this is farther'
  return (
    <div>
      <Son 
        name={name}
        age={18}
        isTrue={false}
        list={['vue','react']}
        obj={{ name: 'dkyzheng'}}
        cb={()=>{console.log('this is cb')}}
      />
    </div>
  );
} 
...

children

场景
  • 当我们把内容嵌套在子组件标签时,父组件会自动在名为children的prop属性中接收该内容
示例
function Son(props) {
  return <div>this is son, {props.children}</div>
}

function App() {
  const name = 'this is farther'
  return (
    <div>
      <Son>
        <span>this is span</span>
      </Son>
    </div>
  );
} 
...

本文作者:505donkey

本文链接:https://www.cnblogs.com/505donkey/p/18391183

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   505donkey  阅读(27)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起