React Ts 实战记录

163 阅读1分钟

webpack 引入别名@报错

craco.config.js

// craco.config.js
const { resolve } = require('path')
webpack: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }

tsconfig.json

//tsconfig.json
// 根级别

"extends": "./paths.json"

paths.json

// paths.json
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@/*": [
        "*"
      ]
    }
  }
}

styled-components 传递属性报错

const Span = styled.span`
  display: inline-block;
  color: ${(props: { currentNumber: number;}) =>
    props.currentNumber % 2 === 0 ? '#fff' : '#fff'};
  animation: ${(props: { once: boolean }) => !props.once && magic}
    ${(props: { currentNumber: number }) => 0.5 + props.currentNumber * 0.1}s
    ease;
`
<Span
  key={+new Date() * Math.random()}
  currentNumber={index}
  once={once}
>

起初上面这种写法ts报了一堆错误报错 发现需要在第一次使用props时,把所有的类型都要声明;改为如下写法ok 及(props: { currentNumber: number; once: boolean },需要把 once也要声明

const Span = styled.span`
  display: inline-block;
  color: ${(props: { currentNumber: number; once: boolean }) =>
    props.currentNumber % 2 === 0 ? '#fff' : '#fff'};
  animation: ${(props: { once: boolean }) => !props.once && magic}
    ${(props: { currentNumber: number }) => 0.5 + props.currentNumber * 0.1}s
    ease;
`