The problem of data transfer between react parent component and child component

1. The parent component passes data to the child component

Two forms of child components to accept values ​​from parent components

The code is as follows (example):

import React from 'react'

// 函数式子组件
function FSon(props) {
    
    
  console.log(props)
  return (
    <div>
      子组件1
      {
    
    props.msg}
    </div>
  )
}

// 类子组件
class CSon extends React.Component {
    
    
  render() {
    
    
    return (
      <div>
        子组件2
        {
    
    this.props.msg}
      </div>
    )
  }
}
// 父组件
class App extends React.Component {
    
    
  state = {
    
    
    message: 'this is message'
  }
  render() {
    
    
    return (
      <div>
        <div>父组件</div>
        <FSon msg={
    
    this.state.message} />
        <CSon msg={
    
    this.state.message} />
      </div>
    )
  }
}

export default App

Summarize

The this keyword should be added to the class component.
props can pass arbitrary data: numbers, strings, booleans, arrays, objects, functions, JSX. Then the attributes corresponding to the binding of subcomponents in the parent component are as follows:
insert image description here
How to use in subcomponents:
insert image description here
However, the use of data above is too troublesome. Generally, props are deconstructed and assigned in advance, and then used directly:
insert image description here

2. The child component passes data to the parent component

The child component uses props to call the function passed by the parent component first. When the child component is triggered, the data that the child component wants to pass is put in as the actual parameter of this function, so that the function in the parent component will be passed in when it is executed. ginseng. In fact: the function in the parent component goes to the child component to "walk around" and bring a parameter back for execution.


import React from 'react'

// 子组件
function Son(props) {
    
    
 function handleClick() {
    
    
   // 调用父组件传递过来的回调函数 并注入参数
   props.changeMsg('this is newMessage')
 }
 return (
   <div>
     {
    
    props.msg}
     <button onClick={
    
    handleClick}>change</button>
   </div>
 )
}


class App extends React.Component {
    
    
 state = {
    
    
   message: 'this is message'
 }
 // 提供回调函数
 changeMessage = (newMsg) => {
    
    
   console.log('子组件传过来的数据:',newMsg)
   this.setState({
    
    
     message: newMsg
   })
 }
 render() {
    
    
   return (
     <div>
       <div>父组件</div>
       <Son
         msg={
    
    this.state.message}
         // 传递给子组件
         changeMsg={
    
    this.changeMessage}
       />
     </div>
   )
 }
}

export default App

Guess you like

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