gpt4 book ai didi

reactjs - 如何在无状态组件上设置 `contextType`

转载 作者:行者123 更新时间:2023-12-03 13:28:52 24 4
gpt4 key购买 nike

我正在使用 React 上下文新 API,如下代码所示。最后一行将把上下文注册到我的组件中。我想知道如何将 contextType 用于无状态组件?

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

我尝试了下面的代码,但它似乎不起作用。组件中的上下文是空对象。

const MyClass = (props, context) => {
...
}
MyClass.contextType = MyContext;

最佳答案

没有办法用 contextType 来做到这一点。
您应该将 contextConsumer 与 renderProps 模式或 React 的 useContext Hook (在 React 16.8 中引入)结合使用

第一个看起来像这样:

const MyClass = (props) => {
return (
<myContext.Consumer>
{({name}) => <View>{name}</View>}
</myContext.Consumer>
)
}

第二种(首选)方法如下所示:

import React, {useContext} from 'react';

const MyClass = (props) => {
const {name} = useContext(myContext)
return <View>{name}</View>
}

关于reactjs - 如何在无状态组件上设置 `contextType`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54721441/

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