Data transfer problem between react brother components

1. Brother components transfer data

insert image description here
In fact, the principle of son-to-father and father-to-son is comprehensively used: sonA——>parent component——>sonB

The code is as follows (example):

import React from 'react'

// 子组件A
function SonA(props) {
    
    
  return (
    <div>
      SonA
      {
    
    props.msg}
    </div>
  )
}
// 子组件B
function SonB(props) {
    
    
  return (
    <div>
      SonB
      <button onClick={
    
    () => props.changeMsg('new message')}>changeMsg</button>
    </div>
  )
}

// 父组件
class App extends React.Component {
    
    
  // 父组件提供状态数据
  state = {
    
    
    message: 'this is message'
  }
  // 父组件提供修改数据的方法
  changeMsg = (newMsg) => {
    
    
    this.setState({
    
    
      message: newMsg
    })
  }

  render() {
    
    
    return (
      <>
        {
    
    /* 接收数据的组件 */}
        <SonA msg={
    
    this.state.message} />
        {
    
    /* 修改数据的组件 */}
        <SonB changeMsg={
    
    this.changeMsg} />
      </>
    )
  }
}

export default App

key point

While executing the parameter newMsg (data) from the child component in the parent component, the data is assigned to the state data of the parent component in the function, and then the state data of the parent component is bound to another child component property:

// 父组件提供状态数据
  state = {
    
    
    message: 'this is message'
  }
// 父组件提供修改数据的方法
  changeMsg = (newMsg) => {
    
    
    this.setState({
    
    
      message: newMsg
    })
  }

Guess you like

Origin blog.csdn.net/qq_37967853/article/details/127907773