react 父子组件传值——父传子

有兴趣的小伙伴可以加Q群 879108483 互相学习

1.使用props传值

具体实现

import React, { Component } from 'react';

/**父组件 */
export default class Parent extends Component {
    state = {
        msg: 1
    }
    render() {
        return (
            <div onClick={() => this.setState({ msg: this.state.msg + 1 })} >
                {/* 子组件 */}
                <Child msg={"传递给子组件的消息:" + this.state.msg.toString()} />
            </div>
        );
    }
}

/**子组件 */
class Child extends Component {
    // 默认的props 可写可不写
    static defaultProps = {
        msg: 1
    }
    render() {
        return (
            <div>
                {/* 通过props传递过来的参数 */}
                {this.props.msg}
            </div>
        )
    }
}

2.使用context (上下文)

Context被归类为高级部分(Advanced),属于React的高级API,但官方并不建议在稳定版的App中使用Context。实际上很多优秀的组件都是通过context来实现的,比如antd的主题样式。用好context可以使项目更灵活。
Context 不仅仅适用于父传子,还可以用来作为跨级传递数据,比如父组件传孙子组件。如果要使用props达到这个效果就要层层传递props。 下面看看context实现方式

  1. 简单使用 (老方法)
import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**父组件 */
export default class Parent extends Component {
    state = {
        msg: 0
    }
    // 声明Context属性
    static childContextTypes = {
        // 数字类型
        msg: PropTypes.number,
        // 方法
        method: PropTypes.func
    }

    // 返回Context对象,约定好方法
    getChildContext() {
        return {
            msg: this.state.msg,
            method: () => "返回来的信息"
        }
    }
    render() {
        return (
            <div onClick={() => this.setState({ msg: this.state.msg + 1 })} >
                {/* 子组件 */}
                <Child />

                {/* 无状态子组件 */}
                <ChildStateLess />
            </div>
        );
    }
}

/**子组件 */
class Child extends Component {
    // 声明需要使用的Context属性 必写 不然听过this.context.xxx 取出来的值为undefind
    static contextTypes = {
        msg: PropTypes.number
    }
    render() {
        return (
            <div>
                {/* 通过props传递过来的参数 */}
                {this.context.msg}
                {/* 孙子组件 */}
                <GrandsonComponent />
            </div>
        )
    }
}


/**无状态组件 */
const ChildStateLess = (props, context) => {
    return (
        <div style={{ color: "red" }} >
            {context.msg}
        </div>

    )
}
/**为无状态组件声明需要使用的Context属性 */
ChildStateLess.contextTypes = {
    msg: PropTypes.number
}

/**孙子组件 */
class GrandsonComponent extends Component {
    // 声明需要使用的Context属性 必写 不然听过this.context.xxx 取出来的值为undefind
    static contextTypes = {
        msg: PropTypes.number
    }
    render() {
        return (
            <div style={{ color: "green" }} >
                {/* 通过props传递过来的参数 */}
                {this.context.msg}
            </div>
        )
    }
}
  1. 使用<React. createContext> Api创建
import React from 'react';

const ExampleContext = React.createContext({
    msg: 0,
    method: () => "method"
});

此ExampleContext通过React.createContext创建,这个Context对象包含两个组件,<Provider />和<Consumer />。
两个API代替了getChildContext、childContextTypes、contextTypes这些繁琐的api,更符合react的设计理念。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

const ExampleContext = React.createContext('ExampleContext');


class ExampleProvider extends Component {
    state = {
        msg: 0
    }
    render() {
        return (
            <div onClick={() => {
                this.setState({ msg: this.state.msg + 1 })
            }} >
                <ExampleContext.Provider value={{ msg: this.state.msg, method: () => { } }} >
                    <Child />
                    <ChildStateLess />
                </ExampleContext.Provider>
            </div>
        );
    }
}

/**子组件 */
class Child extends Component {
    render() {
        return (
            <ExampleContext.Consumer>
                {
                    (context) => (
                        <div>
                            {/* 通过props传递过来的参数 */}
                            {context.msg}
                            {/* 孙子组件 */}
                            <GrandsonComponent />
                        </div>
                    )
                }
            </ExampleContext.Consumer>
        )
    }
}

/**无状态组件 */
const ChildStateLess = (props, context) => {
    return (
        <ExampleContext.Consumer>
            {
                (context) => (
                    <div style={{ color: "green" }} >
                        {/* 通过props传递过来的参数 */}
                        {context.msg}
                        {/* 孙子组件 */}
                    </div>
                )
            }
        </ExampleContext.Consumer>
    )
}
/**为无状态组件声明需要使用的Context属性 */
ChildStateLess.contextTypes = {
    msg: PropTypes.number
}

/**孙子组件 */
class GrandsonComponent extends Component {
    render() {
        return (
            <ExampleContext.Consumer>
                {
                    (context) => (
                        <div style={{ color: "red" }} >
                            {/* 通过props传递过来的参数 */}
                            {context.msg}
                            {/* 孙子组件 */}
                        </div>
                    )
                }
            </ExampleContext.Consumer>
        )
    }
}


export default ExampleProvider;
  1. 直接使用context的地方
    生命周期:
    1.componentWillReceiveProps(nextProps, nextContext)
    2.shouldComponentUpdate(nextProps, nextState, nextContext)
    3.componetWillUpdate(nextProps, nextState, nextContext)

构造函数: constructor(props, context)

web前端、react交流群:879108483

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。