【问题标题】:Why isn't my Styled component data getting passed into my Button for React?为什么我的 Styled 组件数据没有传递到我的 React 按钮?
【发布时间】:2021-01-17 19:23:05
【问题描述】:

所以我用 styled-components 创建了这个按钮,它是一个 react-scroll 链接

import { Link } from 'react-scroll';

export const Button = styled(Link)`
  border-radius: 50px;
  background: ${({ primary }) => (primary ? 'red' : 'blue')};
`;

所以在我的英雄部分,这些道具可以正常工作

<Button
  to="signup"
  smooth={true}
  duration={500}
  spy={true}
  exact="true"
  offset={-80}
  primary="true"
  dark="true"
>
  Sign Up
</Button>;

但在我的另一部分中,我使用带有数据的对象来获取值,并且由于某种原因,它们没有应用主对象

const Main = ({ primary, dark }) => {
  return (
    <Button
      to="home"
      dark={dark ? 'true' : 'false'}
      primary={primary ? 'true' : 'false'}
    >
      {buttonLabel}
    </Button>
  );
};

然后在我的主要部分的 data.js 文件中,我传入这个值

export const dataOne = {
  primary: false,
  dark: true,
};

export const dataTne = {
  primary: true,
  dark: false,
};

所以如果我 console.log 主要,它只会对两者都说 false。

如果 primary 为真,我将我的按钮元素更新为橙色,这会将我的所有按钮更改为橙色,但是为什么我的 data.js 文件无法将我的数据传输过来并没有任何意义背景颜色。

对我来说,让数据通过的唯一方法是,如果我在主要部分内部创建一个样式化的组件,而不是将它放在外部?

【问题讨论】:

标签: reactjs styled-components


【解决方案1】:

您传递的是字符串,而不是布尔值,通过使用 {} 而不是引号来更改为道具分配值的方式

<Button
  to="signup"
  smooth={true}
  duration={500}
  spy={true}
  exact={true}
  offset={-80}
  primary={true}
  dark={true}
>
  Sign Up
</Button>;
const Main = ({ primary, dark }) => {
  return (
    <Button
      to="home"
      dark={dark}
      primary={primary}
    >
      {buttonLabel}
    </Button>
  );
};

它适用于 Hero 部分,因为任何非空字符串,在本例中为“true”,都是 truthy,所以您的条件 (primary ? 'red' : 'blue') 有效,如果您更明确地定义它,它将停止工作 primary === true

您不妨重新考虑您的组件设计https://spicefactory.co/blog/2019/03/26/how-to-avoid-the-boolean-trap-when-designing-react-components/

【讨论】:

  • 为了避免这些错误,花点时间学习打字稿是一项不错的投资
【解决方案2】:

所以我发现对于样式化的组件,它说错误不能将 true 传递给非布尔值,你必须改用数字

<Button
  to="home"
  smooth={true}
  duration={500}
  spy={true}
  exact="true"
  offset={-80}
  primary={primary ? 1 : 0}
  dark={dark ? 1 : 0}
  dark2={dark2 ? 1 : 0}
></Button>;

所以现在我的数据值在我使用 1 : 0 时传入

不知道为什么常规字符串不这样做,但如果有人知道,请随时在下面发表评论

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2021-06-30
    • 2021-04-20
    • 1970-01-01
    相关资源
    最近更新 更多