0

我设置的变量 (bgColor,txtColor) 并没有始终如一地进入 styled-jsx。我附上了一个屏幕截图,您可以在其中看到 console.log 没有显示正在呈现的相同值。

我相信我没有得到关于 styled-jsx 的一些东西。不知道为什么这不起作用。

const Badge = (props) => {
  const { variation = null, size = null } = props;

  let bgColor = "#eeeeee";
  let txtColor = "#000000";
  switch (variation) {
    case "red":
      bgColor = "#FADBD8";
      txtColor = "red";
      break;
    case "green":
      bgColor = "#D5F5E3";
      txtColor = "green";
      break;
  }
  /* Test to see what our values are */
  console.log(`props.children=${props.children}, bgColor=${bgColor}, txtColor=${txtColor}`)
  return (
    <span className="badge">
      {props.children}

      {/* My colors and text in the CSS do not match the vars printed to cosole above */}
      <style jsx>{`
        .badge {
          text-transform: capitalize;
          display: inline-block;
          padding: 0.2rem 0.4rem;
          border-radius: 3px;
          background-color: ${bgColor};
          color: ${txtColor};  
        }

      `}</style>
    </span>
  );
};

这是组件渲染错误的示例... 在此处输入图像描述

更新 深入挖掘。看起来有时它会将相同的生成 JSX 样式分配给应该是不同颜色的项目。关于为什么将其分配给同一类的任何想法?(附上图片) 在此处输入图像描述

4

1 回答 1

0

我猜它在服务器和客户端的渲染样式之间不同步。您可以申请useState解决问题。

const [bgColor, setBgColor] = useState('#eeeeee')

switch(variation) {
  case 'red':
    setBgColor('#FADBD8')
    break
  case 'green'
    setBgColor('#D5F5E3')
    break
}
于 2020-03-14T00:16:40.077 回答