美文网首页
react学习(6)

react学习(6)

作者: 哆啦C梦的百宝箱 | 来源:发表于2023-12-21 09:59 被阅读0次

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


image.png
  • 父传子
    1:父组件传递数据;在子组件标签上绑定数据
    2:子组件接收数据;子组件通过props接收数据
function Son(props){
  return <div>{props.name}</div>
}

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

props说明
1:props可以为任意值:数字,字符串,布尔值,对象,数组,函数,jsx等
2:props是只读对象:子组件只能读取props中的数据,不能直接进行修改,父组件的数值只能父组件修改。
3:特殊的props :children

function Son(props){
  console.log(props.children);
}
<Son><span>这是一个span</span></Son>
  • 子传父
    核心思路:在子组件中调用父组件传递过来的函数,并传递实参
//子组件
function Son({onGetSonMsg}){
  const sendMsg ='this is son msg';
  return <button onClick={()=>onGetSonMsg(sendMsg)}>发送</button>
}
//父组件
function App(){
  const getMsg=(msg)=>{
      console.log(msg);
  }
  return <div><Son onGetSonMsg={getMsg}></Son></div>
}

相关文章

网友评论

      本文标题:react学习(6)

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