react 父子通信

 父组件

import React, { Component } from 'react'
import Child from './child'
export default class Home extends Component {
    constructor(props) {
    super(props);
    this.state = {}
    }
    getObj=()=>{
        const obj2={
            name:'李四',
            age:33,
            education:'博士',
            sex:'男'
        }
        return obj2
    }
    render() {
        const obj={
            name:'张三',
            age:30,
            education:'博士',
            sex:'男'
        }
        return (
        <div style={{height:'100%',backgroundColor:'#fff'}}>
            <h2 style={{fontSize:'30px'}}>父组件</h2>
            <div>父传子,子用父亲里面的数据</div>
            <Child  obj={obj} setFun={this.getObj}/>
            <div>姓名:{}</div>
        </div>
        )
    }
}

子组件

import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class Child extends Component {
    static propTypes={
       obj:PropTypes.object.isRequired, //isRequired 是否必须,不添加就是可以不传
       setFun:PropTypes.func.isRequired
    }
    constructor(props) {
        super(props);
        const obj=this.props.obj
        
        this.state = {
             obj:obj,
             obj2:{},
             name:'321321'
        }
        this.inputRef = React.createRef();
    }
    eventClick=()=>{
        const obj2=this.props.setFun()
        this.setState({obj2})
    }
    methodToParent=()=>{
        console.log(1111)
    }
    render() {
        const {obj,obj2}=this.state
        const {name,age,education,sex}=obj
        return (
        <div style={{height:'100%',backgroundColor:'#fff'}}>
            <div style={{border:'1px solid #ccc',padding:'5px',width:'200px',backgroundColor:'#f1f1f1'}}>
                <p>姓名:{name}</p>
                <p>年纪:{age}</p>
                <p>学历:{education}</p>
                <p>性别:{sex}</p>
            </div>
            <div style={{marginTop:'20px'}}>
                <h2>父传子,子调用父亲函数产生的数据
                    <span 
                    onClick={this.eventClick} 
                    style={{backgroundColor:'#008255',padding:'0px 10px',color:'#fff',marginLeft:'10px',cursor:'pointer'}}
                    >点击</span>
                </h2>
                <p>姓名:{obj2.name}</p>
                <p>年纪:{obj2.age}</p>
                <p>学历:{obj2.education}</p>
                <p>性别:{obj2.sex}</p>
            </div>
            <div style={{marginTop:'20px'}}>
                <h2>子传父,父亲调用子里面的数据</h2>
                <input type="text" value={this.state.name} onChange={(e) => this.setState(e.target.value)} ref={this.inputRef} />
            </div>
        </div>
        )
    }
}

猜你喜欢

转载自www.cnblogs.com/binmengxue/p/12573914.html