gpt4 book ai didi

reactjs - 如何在渲染之外从 React Context Consumer 获取数据

转载 作者:行者123 更新时间:2023-12-03 13:11:43 26 4
gpt4 key购买 nike

我正在使用新的 React Context API,我需要从 Context.Consumer 变量获取消费者数据,而不是在渲染方法中使用它。无论如何,我可以实现这个目标吗?

举例说明我想要什么:

console.log(Context.Consumer.value);

到目前为止我测试的内容:上面的示例测试了 Context.Consumer currentValue 和 Context Consumer 具有的其他变量,尝试将 Context.Consumer() 作为函数执行,但没有成功。

有什么想法吗?

最佳答案

更新

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

但是,该组件只能访问单个上下文。为了使用多个上下文值,请使用 render prop 模式。更多关于Class.contextType .

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

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

渲染 Prop 模式

当我从问题中了解到,要在组件内部但在渲染外部使用上下文时,请创建一个 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);

关于reactjs - 如何在渲染之外从 React Context Consumer 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com