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

时间:2019-02-16 08:55:56

标签: reactjs

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

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

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

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

2 个答案:

答案 0 :(得分:2)

无法使用contextType进行操作。
您应该使用带有renderProps模式的contextConsumer或React的useContext钩子(在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>
}

答案 1 :(得分:0)

您必须导入 useContext,然后定义一个变量,用您定义的上下文的参数填充 useContext 的输出。

import React, {useContext} from 'react';

const MyClass = (props) => {
    const context = useContext(yourContext)
    return <p>{context.name}</p>
}