React子传父

父子之间的通信:子传父

子组件:

import React, { Component } from 'react'

export default class CounterButton extends Component {
    render() {
        const {increment} = this.props;    //通过props拿到父组件传过来的事件
        return (
            <button onClick={increment}>+1</button>
        )
    }
}

父组件:

 

import React, { Component } from 'react'
import CounterButton from '../CounterButton/CounterButton';
export default class Header extends Component {
    constructor(props){
        super(props);
        this.state={
            title:'我是标题',
            counter:0
        }
    }
    render() {
        const{title,counter} = this.state
        return (
            <div>
                <h2>当前我们的计数{counter}</h2>
                <CounterButton increment={this.increment}/>  //子组件
                <h3 title={title}>我是标题</h3>
            </div>
        )
    }
    increment=()=>{
        console.log('被调用');
        this.setState({
            counter:this.state.counter + 1
        })
    }
}

 

组件之间的通信例子:

 

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...