样式化组件和 Typescript 类型错误

Styled Components & Typescript type error

我已经在 react-native 中成功设置了 styled-components,但是我现在使用的是 react-native-web 并且无法在这个非常简单的示例中让 styled-components 在 web 上工作:

import * as React from 'react';
import styled from 'styled-components';

export default class View extends React.PureComponent {
  public render() {
    return (
      <Container>
        <h1>Hey</h1>
      </Container>
    );
  }
}

const Container = styled.div;

我收到此错误:

Type error: JSX element type 'StyledComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, a...' is not a constructor function for JSX elements.
Property 'render' is missing in type 'StyledComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, a...'.  TS2605
> 11 |       <Container>

这是我的 tsconfig.json:

"target": "es6",
"jsx": "preserve",
"module": "esnext",
"sourceMap": true,
"outDir": "dist",
"types": [
  "react",
  "react-native",
  "jest"
],
"skipLibCheck": true,
"lib": [
  "es2015.promise",
  "esnext",
  "dom"
],
"alwaysStrict": false,
"downlevelIteration": true,
"strict": false,
"strictNullChecks": false,
"allowJs": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true

还有我的 package.json:

...
"devDependencies": {
  ...
  "@types/react": "^16.7.20",
  "@types/react-dom": "^16.7.20",
  "@types/react-native": "^0.52.25",
  "typescript": "^2.9.2"
},
"dependencies": {
  ...
  "react": "16.3.1",
  "react-dom": "^16.7.0",
  "styled-components": "^3.4.5",
}

我试过 rm -rf node_modules; rm package-lock.json; npm install 没用。

这里可能遗漏了一些简单的东西,但是有人有什么想法吗?不确定我还能提供哪些其他信息。

您需要使用 React Native 组件而不是标准 HTML 标签。 您将使用 styled.View 而不是 styled.div。此外,您还必须使用 React Native 的 Text 组件来替换标准 HTML 标签,这些标签将保存文本数据,例如 <H1>.

所以,这就是您的代码应转换成的内容

import * as React from 'react'
import { Text } from 'react-native'
import styled from 'styled-components/native'

export default class View extends React.PureComponent {
    render() {
        return(
            <Container>
                <Text>Hey</Text>
            </Container>
        )
    }
}

const Container = styled.View