react子组件给父组件传东西

父组件引用子组件的时候,加回调

然后在子组件中通过this.props.回调函数    调用这个方法

下面这个改变颜色的例子

import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss'


class Child extends React.Component {
    handleClick(){
        this.props.colorChange('green')
    }
    render() {
        return <div>
            <p>父组件的背景颜色:{this.props.bgColor}</p>
            <button onClick={(e)=>this.handleClick(e)}>改变颜色</button>
        </div>
    }
}


class Father extends React.Component {
    constructor(props){
        super(props);
        this.state={
            bgColor:'#999'
        }
    }
    bgColorChange(color){
        this.setState({
            bgColor:color
        })
    }

    render() {
        return (<div style={{background:this.state.bgColor}}>
            <Child  bgColor={this.state.bgColor} colorChange={(color)=>this.bgColorChange(color)}/>
        </div>)
    }
}


ReactDOM.render(
    <div>
        <Father/>
    </div>,
    document.getElementById('app')
);

猜你喜欢

转载自blog.csdn.net/gloria199091/article/details/80197467