青いやつの進捗日記。

メモとしてべんきょうのしんちょくをかいていきます。あとで自分が検索しやすいもん

styled-componentsですごい頻度でpropsを更新し続けていたらattrsメソッドを使えと怒られた

react_devtools_backend.js:2842 Over 200 classes were generated for component Seekbar__Preview with the id of "Seekbar__Preview-sc-16onun1-1".
Consider using the attrs method, together with a style object for frequently changed styles.
Example:
  const Component = styled.div.attrs(props => ({
    style: {
      background: props.background,
    },
  }))`width: 100%;`

ってconsoleに出て…attrsってなんやねんと思い調べる

styled-componentsの使い方(パッとわかりやすく、色々なパターンを説明することを目指しています) · GitHub

blog.gaji.jp

もともとはこう書いていて

type PreviewProps = {
  currentTime: number
  duration: number
}
const Preview = styled.div<PreviewProps>`
  position: absolute;
  top: 0;
  left: 0;
  height: 4px;
  width: ${(props) => props.currentTime / props.duration}%;
`

これを以下に直せ、ということだったみたい

type PreviewProps = {
  currentTime: number
  duration: number
}
const Preview = styled.div.attrs<PreviewProps>((props) => ({
  style: {
    width: `${props.currentTime / props.duration}%`
  }
}))<PreviewProps>`
  position: absolute;
  top: 0;
  left: 0;
  height: 4px;
`

こうするとPropsが更新されてもクラス名が変わらなくなりHTMLに直に値が入るようになる

f:id:XxGodmoonxX:20211002130605p:plain

200回以上クラスを生成していると怒ってくれるんだな…すごいね…その頻度で生成し続けたらパフォーマンス的に影響あるから、ということなのだろうな…