#15 高阶组件 + context


  • 0

    主要是理解高阶组件其实就是包裹了一个组件的组件,然后context不是说通过继承来共享的,而是通过包裹来共享的。

    const makeProvider = (any_arg) => {
      return (AComponent) => {
        class WrapperComponent extends Component {
          static childContextTypes = {
            data: PropTypes.object
          }
           
          getChildContext () {
            return {
              data: any_arg
            }
          }
          
          render() {
            return (<AComponent />)
          }
        }
        
        return WrapperComponent;
      }
    }
    

  • 0

    const makeProvider = data => WrapperComponent => {
      return class NewComponent extends Component {
        static childContextTypes = {
          data: PropTypes.object.isRequired,
        }
    
        getChildContext() {
          return {
            data,
          }
        }
    
        render() {
          return (
            <div>
              <WrapperComponent />
            </div>
          )
        }
      }
    }
    

  • 0

    <code>
    const makeProvider = (data) => (WrapComponent) => {
    return class extends Component {
    static childContextTypes = {
    data: PropTypes.object
    }
    constructor() {
    super()
    this.state = {data}
    }
    getChildContext () {
    return { data: this.state.data }
    }
    render() {
    return <WrapComponent />
    }
    }
    }

    </code>


  • 0

    const makeProvider = data => Comp => class extends Component {
      static childContextTypes = {
        data: PropTypes.any
      }
      
      getChildContext () {
        return { data }
      }
    
      render () {
        return <Comp {...this.props}/>
      }
    }
    

  • 0

    @贾维尔麦基 getChildContext()要返回的是一个对象不是一个函数,改成{data:this.state.data}就可以了


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待