react 父子通信

202 阅读1分钟

父传子

import React, { Component } from 'react';
class App extends Component {
 constructor(props) {
   super(props)
   this.state = {
     toSon: "父传子的值"
   }
 }

 render() {
   return (

     <div
     >
       father
     < Son
         getvalue={this.state.toSon}
       ></Son >
     </div >
   )
 }
}


class Son extends Component {
 constructor(props) {
   super(props)
   this.state = {
   }
 }

 render() {
   return (

     <div>
       <div>{this.props.getvalue}</div>   //父传子的值
       son
     </div>
   )
 }
}


export default App;

子传父

import React, { Component } from 'react';
import './reactCss.css'


class App extends Component {
 constructor(props) {
   super(props)
   this.state = {
   }
 }

 render() {
   return (

     <div
     >
       father
     < Son
          event={(v) => {
            console.log('v', v) //子传父的值
          }}


       ></Son >
     </div >
   )
 }
}


class Son extends Component {
 constructor(props) {
   super(props)
   this.state = {
     value: '子传父的值'
   }
 }

 render() {
   return (

     <div>
       <button onClick={this.sonClick.bind(this)}>  click</button> 
       son
     </div>
   )
 }
 sonClick = () => {
   this.props.event(this.state.value)
 }
}


export default App;