首页 > 解决方案 > 关于 React 上下文:“{}”类型中缺少属性“children”,但在“ConsumerProps”类型中是必需的

问题描述

我是 React Context 的新手,下面的代码可以工作,但总是会出现类型错误。

<AppContext.Consumer>
     {({ value }: { value: string }) => <div>{value}</div>}
</AppContext.Consumer>

“{}”类型中缺少属性“children”,但在“ConsumerProps<...>”类型中是必需的。ts(2741) index.d.ts(342, 9):此处声明了“children”。

interface ConsumerProps<T> {
        children: (value: T) => ReactNode;
    }

我认为{({ value }: { value: string }) => <div>{value}</div>}应该被检测为只是 ConsumerProps 想要的孩子,但事实并非如此。如果我写这样的代码

        <AppContext.Consumer
          children={() => {
            return <View />
          }}
        />

有一个 eslint 约束

请勿将儿童作为道具传递。相反,在开始标签和结束标签之间嵌套子元素。eslintreact/no-children-prop

我怎么能在不改变 eslint 约束的情况下解决这个问题。

标签: reactjstypescriptreact-context

解决方案


推荐阅读