react学习(6)

2023-12-21  本文已影响0人  哆啦C梦的百宝箱

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


image.png
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>
}
上一篇 下一篇

猜你喜欢

热点阅读