一.父组件向子组件传值

父组件(Father)

子组件(Children)

二.子组件向父组件传值

父组件(Father)

 

子组件(Children)

父组件(Father代码)

import React, {Component} from 'react';
import { withRouter } from 'react-router-dom';
const Children = React.lazy(() => import('./../Children'));
class Father extends Component{
    state = {
        info: 'hello'
    }
    handleChangeName=(name)=>{
        this.setState({info: name})
    }
    render(){
        return (
            <div>
                {this.state.info }
                <Children handleChange={ this.handleChangeName } />
            </div>
        )
    }
}
export default withRouter(Father);

 子组件(Children代码)

import React, {Component} from 'react';
import { withRouter } from 'react-router-dom';
class Children extends Component{
    handleClik=()=>{
        const { handleChange } = this.props
        handleChange('萝莉')
    }
    render(){
        return (
            <div>
                <div onClick={ this.handleClik } > { this.props.name }点击改变name </div>
            </div>
        )
    }
}
export default withRouter(Children);

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐