react传参

基本传参props

传递数据

在子组件中

this.props.age获取数据

传方法

setAage = v =>this.setState({age:v})

在子组件使用

this.props.setAge(15)}>

context

上下文传递参数

特点:引入的context 数据 是时时更新  当一个数据发生改变所有引用数据的视图都会自动更新

父组件

1. 导入类型检测

import PropTypes  from 'prop-types';

2. 定义导出的数据类型

    static childContextTypes = {

        color:PropTypes.string, // 字符串类型

        setColor:PropTypes.func,// 方法类型

    }

3.  获取需要传参的数据

    getChildContext(){

        return {

            color:this.state.color,

            setColor:v=>this.setState({color:v})}

    }

子孙组件

1. 定义上下文数据类型

    static contextTypes = {

        color:PropTypes.string, // 字符串类型

        setColor:PropTypes.func,// 方法类型

    }

2. 使用上下文数据

Child组件

使用上下文方法

) }

redux react-redux

全局数据状态共享

vuex就是有参考redux的

1 安装  npm i redux react-redux

2. 从 react-redux导入Provider

import {Provider} from 'react-redux';

3. 把根组件替换为

   

4. 在Provider中添加数据仓库

5. 编写store仓库并导入仓库

6.编写store

1. redux导入

2. reducer 初始数据方法

3. actions 处理数据动作

4. 导出仓库

7.在组件中使用

1.导入连接

2.导出组件

export default connect(mapStateToProps,mapDisPatchToProps)(Detail)

mapStateToProps 组state数据映射为 组件的props

mapDisPatchToProps 把state中的方法映射诶porps中的方法

你可能感兴趣的:(react传参)