react 父子相互传值方法

2024-01-31  本文已影响0人  糖醋里脊120625
1. 父子相互传值函数方法
1.父组件

import React, { useState,useEffect } from 'react'
import { Link, withRouter } from 'react-router-dom'
import Child from './child4';
import { Result, Button } from 'antd'
const NoEorr = () => {
  const state = {
    msg:'我是父组件的信息' //1.父组件准备数据
  }
  const [myname, setMyname] = useState("冠军侯")
  function getChidMsg(childVal){
    setMyname(childVal)
    console.log(childVal)
  }
return ( 
<>
  <Child pMsg={state.msg}  getMsc={getChidMsg}></Child>
  <div>
  <Button type="primary">{myname}</Button>
  </div>
  
   </>
   )
   
  }
export default NoEorr



2.子组件

import React from 'react'
import { Link } from 'react-router-dom'
import { Result, Button } from 'antd'
const Sonny = (prop) => {
  console.log(prop)
  const {pMsg} = prop
  function handClick(){
     console.log(prop)
     prop.getMsc("我从子组件来")
  }
 return (
      <>
        <Button type="primary" onClick={handClick}>这个是子组件</Button>
        <Button type="primary">{pMsg}</Button>
      </>
 )
}
      

export default Sonny

2,还有一种父子相互传值的

1.父组件
import React, { Component } from 'react'
import Son from './child4'
export default class Father extends Component {
  constructor() {
    super()
    this.state = {
      message: 'hello',
      sonVal: null
    }
  }
  render() {
    return (
      <div className="father-ri" id="father">
        <h1>Father组件</h1>

        <button onClick={() => { this.setState({ message: 'world' }) }} > 修改 </button>
        <p>选择了那种水果:{this.state.sonVal}</p>
        <Son data={this.state.message} handle={this.testAction.bind(this)} />

      </div>
    )
  }
  // 接收子组件数据
  testAction(value) {
    console.log(this)
    console.log(value)
    this.setState({ sonVal: value })
  }
}


2.子组件
import React, { Component } from 'react'

export default class Son extends Component {
  constructor() {
    super()

    this.state = {
      select: '苹果'
    }
  }

  render() {
    let arr = ['苹果', '香蕉', '西瓜']

    return (
      <div className="child-ri" id="son">
        <h1>Son组件</h1>
        <p>接收到的值为:{this.props.data}</p>
        {arr.map((item, index) => {
          return (
            <p key={index}>
              {item}:
              <input
                type="radio"
                value={item}
                checked={this.state.select == item}
                onChange={this.inputChange.bind(this)}
              />
            </p>
          )
        })}
      </div>
    )
  }

  inputChange(ev) {
    let value = ev.target.value
    this.setState({ select: value })
    // 调用父组件的方法,将值传递给父组件
    this.props.handle(value)
  }
}

上一篇 下一篇

猜你喜欢

热点阅读