(精华2020年5月24日更新) react基础篇 父组件到孙组件跨级传参

新版:跨级传参最主要是避免每层赋值,也避免用到dva

import React from 'react'
const {Provider,Consumer} = React.createContext('default')
export default class ContextDemo extends React.Component {
    state={
        newContext:'createContext'
    }
  render() {
      const {newContext} = this.state
    return (
        <Provider value={newContext}>
            <div>
                <label>childContent</label>
                <input type="text" value={newContext} onChange={e=>this.setState({newContext:e.target.value})}/>
            </div>
            <Son />
        </Provider>
    )
  }
}
class Son extends React.Component{
    render(){
        return <Consumer>
            {
                (name)=>
                    <div style={{border:'1px solid red',width:'60%',margin:'20px auto',textAlign:'center'}}>
                        <p>子组件获取到的内容:{name}</p>
                        <Grandson />
                    </div>
                
            }
        
        </Consumer>
    }
}
class Grandson extends React.Component{
    render(){
        return <Consumer>
            {
                (name)=>
                    <div style={{border:'1px solid red',width:'60%',margin:'20px auto',textAlign:'center'}}>
                        <p>孙子组件获取到的内容:{name}</p>
                    </div>
                
            }
        
        </Consumer>
    }
}

老项目的方式也介绍一下,利用prop-types

import React from 'react'
import PropTypes from 'prop-types'
class ContextDemo extends React.Component {
    // getChildContext
    state={
        newContext:'createContext'
    }
    getChildContext(){
        return {value:this.state.newContext}
    }
  render() {
      const {newContext} = this.state
    return (
            <div>
                <div>
                    <label>childContent</label>
                    <input type="text" value={newContext} onChange={e=>this.setState({newContext:e.target.value})}/>
                </div>
                <Son />
            </div>
    )
  }
}
class Son extends React.Component{
    render(){
        return <div>
            <p>children:{this.context.value}</p>
        </div>
    }
}
Son.contextTypes = {
    value:PropTypes.string
}
ContextDemo.childContextTypes = {
    value:PropTypes.string
}
export default () => 
  <ContextDemo >
  
  </ContextDemo>
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页