【问题标题】:Consuming React useContext in a class based component in TypeSCript在 TypeSCript 中基于类的组件中使用 React useContext
【发布时间】:2021-06-03 07:38:35
【问题描述】:

我在这样的功能组件中使用我们的 cartContext:

import { CartContext } from '../../contexts/CartContext';

function staticCart(){
    const { increase, decrease, removeProduct } = useContext(CartContext);
    const { total, cartItems, shipping, netTotal, vat, finalTotal } = useContext(CartContext);
    return (
         <React.Fragment>Logic to use the complex cart contexts</React.Fragment>
    )
}

这按预期工作正常。我们有一个基于类的组件,如下所示:

import- statements

class StaticCart extends COmponent<RouteComponentProps<any>, State> {
    protected datatypes
    
    constructor(props: any) {
        ...
    }
    componentDidMount() {
        ...
    }

    render() {
        return (
            <React.Fragment>
                ...
            </React.Fragment>
        )
    }
}

我正在尝试将上述相同的方法(如在功能组件中)添加到类组件中。

我试过了:

【问题讨论】:

    标签: reactjs typescript react-context


    【解决方案1】:

    在 React 中创建上下文将提供两件事,一是 ProviderConsumerProvider 对于类和函数组件保持不变。

    对于功能组件,我们可以将Consumer 替换为useContext。但是对于类组件你需要使用Consumer

    <CartContext.Consumer>
    {(value) => { return ( .... )}}
    </CartContext.Consumer>
    

    【讨论】:

      【解决方案2】:

      我最终使用了这种方法,

      import- statements
      
      class StaticCart extends COmponent<RouteComponentProps<any>, State> {
          protected datatypes
          
          static contextType = CartCOntext;
          constructor(props: any) {
              ...
          }
          componentDidMount() {
              ...
          }
      
          render() {
              const { increase, decrease, removeProduct } = useContext(CartContext);
      const { total, cartItems, shipping, netTotal, vat, finalTotal } = useContext(CartContext);
              return (
                  <React.Fragment>
                      ...
                  </React.Fragment>
              )
          }
      }
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 2021-06-19
        • 2020-10-24
        • 2020-09-29
        • 2018-10-15
        • 2019-11-18
        • 2021-04-18
        相关资源
        最近更新 更多