如何从渲染之外的React Context Consumer获取数据

问题描述 投票:12回答:1

我正在使用新的React Context API,我需要从Context.Consumer变量中获取Consumer数据,而不是在render方法中使用它。无论如何我能做到这一点吗?

例如,我想要的是:

console.log(Context.Consumer.value);

到目前为止我测试的内容:上面的例子,测试了Context.Consumer currentValue和Context Consumer所拥有的其他变量,试图将Context.Consumer()作为一个函数执行而没有工作。

有任何想法吗?

reactjs react-context
1个回答
22
投票

Update

从React v16.6.0开始,您可以使用上下文API,如:

class App extends React.Component {
    componentDidMount() {
       console.log(this.context);
    }
    render() {
       // render part here
       // use context with this.context
    }
}
App.contextType = CustomContext

但是,该组件只能访问单个上下文。要使用多个上下文值,请使用渲染道具模式。关于Class.contextType的更多信息。

如果您使用的是实验性public class fields syntax,则可以使用静态类字段初始化contextType

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

Render Prop Pattern

当我从问题中理解,要在组件内使用上下文但在渲染之外,创建一个HOC来包装组件:

const WithContext = (Component) => {
  return (props) => (
      <CustomContext.Consumer>
           {value =>  <Component {...props} value={value} />}
      </CustomContext.Consumer>
  )
}

然后使用它:

class App extends React.Component {
    componentDidMount() {
       console.log(this.props.value);
    }
    render() {
       // render part here
    }
}
export default WithContext(App);
© www.soinside.com 2019 - 2024. All rights reserved.