动态渲染 React 风格组件时消除警告

2024-03-24

我在浏览器控制台中收到以下警告:

react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically.
You may see this warning because you've called styled inside another component.
To resolve this only create new StyledComponents outside of any render method and function component.

然而我的CSS定位应该是动态的。高度每 5 秒改变一次。

我可以执行以下任一操作吗?

  1. 正确编码,这样就不会显示警告
  2. 或者,在情况 1 不可行时抑制警告
// Height of the div is dynamically calculated every 5 seconds
private randomHeight = () => {
    return Math.floor(Math.random() * 85);
}

// This method is eventually called by the Render method
private getLeftDiv = () => {
    const height = this.randomHeight();

    const keyFrames = keyframes`
          0% {
              left: -120px;
          }
          5% {
              left: -45px;                
          }
          95% {
              left: -45px;                
          } 
          100% {
              left: -120px;
          }
      `
    const HeadDiv = styled.div`
          position: fixed;
          animation: ${keyFrames} 2s linear;
          animation-timing-function: ease-in ;
          left: -120px;
          top: ${height}%;
          transform: rotate(45deg);
      `
    return HeadDiv;
}

您应该声明HeadDiv在当前组件的渲染之外单独设置样式组件,并使用其props将动态值传递给它。

const HeadDiv = styled.div`
    position: fixed;
    animation: ${props => props.keyFrames} 2s linear;
    animation-timing-function: ease-in ;
    left: -120px;
    top: ${props => props.height}%;
    transform: rotate(45deg);
`

您现在可以将动态值传递给HeadDiv的道具。

<HeadDiv keyFrames={keyFrames} height={height} />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

动态渲染 React 风格组件时消除警告 的相关文章

随机推荐