react传参

基本传参 props
<child age={this.state.age}>
在子组件中
this.props.age 获取数据
传参方法

setAge = v=>this.setState({age:v})
<child age={this.state.age} setAge={this.setAge. bind(this)}>

在子组件使用
<h3 onClick= {()=>this.props.setAge(15)}>

上下文传递参数 context
<h3 onClick= {()=>this.props.setAge(15)}>
所有引用数据的视图都会自动更新
父组件
导入类型检测
import PropTypes from 'prop-types';
定义导出的数据类型

static childContextTypes = {
        color:PropTypes.string, // 字符串类型
        setColor:PropTypes.func,// 方法类型
    }

获取需要传参的数据

getChildContext(){
    return{
        color:this.state.color,
        setColor:v=>this.setState({color:v})}
}

子孙组件
定义上下文数据类型

static contextTypes = {
        color:PropTypes.string, // 字符串类型
        setColor:PropTypes.func, //  方法类型
}

使用上下文数据
<h3 style={{color:this.context.cor}}>Child组件</h3>

使用上下文方法
"<button onClick={0=>this.context.setColor('gold')}>
在Provider中添加数据仓库
<Provider store={store}>
编写store

redux导入
reducer 初始数据方法
actions 处理数据动作
导出仓库

在组件中使用
导入连接
导出组件

export default connect(mapStateToProps,mapDisPatchToProps)(Detail)
mapStateToProps 组state数据映射为 组件的props
mapDisPatchToProps 把state中的方法映射porps中的方法
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 基本传参props 传递数据 <child age={this.state.age}> 在子组件中 this.pr...
    char1阅读 278评论 0 0
  • react传参 基本传参 props<child age={this.state.age}>在子组件中this.p...
    一只小丫丫阅读 141评论 0 0
  • 基本传参props 子组件 传递数据<child age={this.state.age}> 获取数据this.p...
    吃肉肉不吃肉肉阅读 537评论 1 1
  • 1.基础传参props 传数据<Child age={this.state.age}> 在子组件中this.pro...
    含含要暴怒阅读 5,770评论 0 0
  • React里的事件参数传递和传统的JS参数有些不一样,需要通过bind方法来绑定参数,第一个参数指向this,第二...
    壹豪阅读 286评论 0 0