reactjs子组件向父组件传值

原理是通过从父组件先传递一个函数给子组件,子组件通过props.func的方法调用父组件的函数达到传值的效果。
父组件

class App extends Component {
  onGreet(age) {
    alert(age)
  }
  render() {
    const user = {
      name: 'Anna',
      hobbies:["Sports", "Readding"]
    }
    return (
      

Hello React!!

); } }

子组件

import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      age:props.initAge,
      status: 0
    }

    setTimeout(() => {
      console.log(this.state.status)
      this.setState({
        status: 1
      })
    }, 3000)
  }

  handlerGreet() {
    this.props.greet(this.state.age);
  }

  onMakeOlder() {
    console.log(this)
    this.setState({
      age:this.state.age + 1
    })
  }


  render() {

    return (
      
Your name is {this.props.name}, age is {this.state.age}

Status:{this.state.status}


); } } Home.propTypes = { name: PropTypes.string, age:PropTypes.number, user:PropTypes.object, greet:PropTypes.func //children: PropTypes.element.isRequired };

你可能感兴趣的:(reactjs子组件向父组件传值)