【问题标题】:How to pass props to an imported component in styled-components如何在 styled-components 中将 props 传递给导入的组件
【发布时间】:2021-05-25 16:06:36
【问题描述】:

这里出现了一个挑战,我正在使用React Native,我需要将道具传递给RectButton,有人知道怎么做吗?

因为它不是标准的 React Native 功能,是从react-native-gesture-handler 导入的,所以我无法通过styled-components 访问它,我想要'like this'的东西:

export const CheckBoxInput = styled(RectButton)<CheckBoxInputProps>`
  border: 1px solid ${h4_app_color};
  width: 20px;
  height: 20px;
  border-radius: 20px;

  ${(props) =>
    props.filled
      ? css`
          background-color: ${h4_app_color};
        `
      : css`
          background-color: white;
        `}
`;

我的道具是这样的:

interface CheckBoxInputProps {
  filled?: boolean;
}

【问题讨论】:

  • 我知道这并不能回答你的问题,但你可以在这里简化你的代码,说 background-color: ${({ filled }) =&gt; filled ? h4_app_color : 'white'} 只是为了让它更具可读性。

标签: android reactjs typescript react-native styled-components


【解决方案1】:

我不明白为什么您在此处检查 filled 道具时遇到问题。通过以下方式将其应用于组件:

<CheckBoxInputProps filled={yourValueHere} />


export const CheckBoxInput = styled(RectButton)<CheckBoxInputProps>`
  border: 1px solid ${h4_app_color};
  width: 20px;
  height: 20px;
  border-radius: 20px;

  ${(props) =>
    props.filled
      ? css`
          background-color: ${h4_app_color};
        `
      : css`
          background-color: white;
        `}
`;

如果您特别想将 prop 传递给组件 &lt;RectButton /&gt; 而不将其应用于其样式,那么您可以这样做:

export const CheckBoxInput = styled(RectButton).attrs((
 {filledValue}: {filledValue: boolean}
) => {
 filled: filledValue   <-- This will pass the value to RectButtons 'filled' prop
}))<CheckBoxInputProps>`

`;

然后像这样使用它:

<CheckBoxInputProps filledValue={yourValueHere} />

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 2017-12-21
    • 2019-02-18
    • 2021-04-06
    • 2021-05-19
    • 2020-03-02
    • 2020-07-09
    • 2020-06-07
    相关资源
    最近更新 更多