react 父组件与子组件的通信

318 阅读1分钟

A:子组件向父组件传参数, 通过事件传参处理

1. hooks 模式

父组件
import { useState } from 'react'
import Son from './son'
export default function Parent(){
    // 获取子组件传递过来的参数
    const [sonData, setSondata] = sueSate('子组件需要改变的值')
    
    return(
        <div>
            <Son setSondata={setSondata}/>
            <p>{sonData}</p>
        </div>
    )
}

子组件
export default function Son(props){
    const {setSondata} = props
    return(
        <div>
           <buttom onClick={setSondata('hello 我是从子组件过来的')}> 向父组件传值  </buttom>
        </div>
    )
}

2. class 模式

父组件,此处通过event.target.value获取子组件的值

const Parent = React.createClass({
    getInitialState: function(){
        return {
            email: ''
        }
    },
    handleEmail: function(event){
        this.setState({email: event.target.value});
    },
    render: function(){
        return (
            <div>
                <div>用户邮箱:{this.state.email}</div>
                <Child name="email" handleEmail={this.handleEmail.bind(this)}/>
            </div>
        )
    }
});

子组件

const Child = React.createClass({
    render: function(){
        return (
            <div>
                请输入邮箱:<input onChange={this.props.handleEmail}/>
            </div>
        )
    }
});

B:父组件获取子组件的方法及参数

父组件

import { useRef } from 'react'
import Son from './son'
const function Parent(){
    const chilRef = useRef()
    // 获取子组件的方法及参数属性
    const handle = () => {
        console.log(chilRef.current)
    }
    return(
        <div>
            <Son chilRef={chilRef}/>
            <buttom onClick={handle}>获取子组件的参数 或者 执行子组件的方法 </buttom>
        </div>
    )
    
}

子组件

import { useImperativeHandle } from 'react'
cons Son(props) {
   useImperativeHandle(props.chilRef, ()=>({
       getData:() => {a:111,b:222}
   }))
   return (
       <div>这里是子组件</div>
   )
}