React 中的父子组件相互通信

React 父组件引用子组件并给子组件传递参数或方法,子组件通过props来获取父组件传递过来的参数,或者触发父组件传递过来的方法来给父组件传值

父组件:

import React, { Component } from 'react'
import B from './B'
export default class A extends Component {
  state={
    data:''
  }
  getData=(data)=>{
    this.setState({data})
  }
  render() {
    const {data} = this.state;
    return (
      
{data}
) } }
子组件:

import React, { Component } from 'react'

export default class B extends Component {
  componentDidMount(){
    const {toMyChild} = this.props;
    toMyChild('to my father');
  }
  render() {
    const {type} = this.props;
    return (
      
{type}
) } }

 

你可能感兴趣的:(React.js)