React-组件通信

1、父子组件通信

(1)父传子(props 传值)

// 父组件
function App() {
  const name = '张三'
  return (
    <div className="App">
      <Son name={name} />
    </div>
  );
}
 
// 子组件
function Son(props) {
  return (
    <div>{ props.name }</div>
  )
}

(2)子传父(回调函数)

// 父组件
function App() {
  const [msg, setMsg] = useState('');
  const getMsg = (data) => {
    console.log(data)
    setMsg(data)
  }
  return (
    <div className="App">
      <div>{ msg }</div>
      <Son onGetMsg={getMsg} />
    </div>
  );
}
 
// 子组件
function Son({ onGetMsg }) {
  return (
    <div>
      <button onClick={() => onGetMsg('子组件给父组件的数据')}>发送数据</button>
    </div>
  )
}

(3)双向数据绑定

// 父组件
function App() {
  const [msg, setMsg] = useState('');
  const getMsg = (data) => {
    console.log(data);
    setMsg(data)
  }
  return (
    <div className="App">
      <div>{ msg }</div>
      <Son msg={msg} onGetMsg={getMsg} />
    </div>
  );
}
 
// 子组件
function Son({ msg, onGetMsg }) {
  return (
    <div>
      <input type="text" value={msg} onChange={(e) => onGetMsg(e.target.value)} />
    </div>
  )
}

2、兄弟组件通信

        通过状态提升实现兄弟组件之间传值,子传父 => 父传子

// 父组件
function App() {
  const [msg, setMsg] = useState('');
  const getMsg = (data) => {
    setMsg(data)
  }
  return (
    <div className="App">
      this is App
      <A onGetMsg={getMsg} />
      <B msg={msg} />
    </div>
  );
}

// 子组件A
function A({ onGetMsg }) {
  return (
    <div>
      this is A component
      <button onClick={() => onGetMsg('AAA')}>send</button>
    </div>
  )
}

// 子组件B
function B(props) {
  return (
    <div>
      this is B component
      { props.msg }
    </div>
  )
}

3、跨层级组件通信

  1. 使用createContext创建上下文对象
  2. 在顶层组件(App)中使用Ctx.Provider组件提供数据
  3. 在底层组件(B)中通过useContext获取消费数据
import { createContext, useContext } from 'react';

// 1.使用createContext创建上下文对象
const MsgContent = createContext();

// 父组件
function App() {
  const msg = '哈哈哈';
  return (
    <div className="App">
      {/* 2.在顶层组件(App)中使用Ctx.Provider组件提供数据 */}
      <MsgContent.Provider value={msg}>
        this is App
        <A />
      </MsgContent.Provider>
    </div>
  );
}

// 子组件A
function A() {
  return (
    <div>
      this is A component
      <B />
    </div>
  )
}

// 孙子组件B
function B() {
  // 3.在底层组件(B)中通过useContext获取消费数据
  const msg = useContext(MsgContent);
  return (
    <div>
      this is B component
      {msg}
    </div>
  )
}

4、任意组件通信(Redux/Zustand)

        见后续文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值