【问题标题】:Add props into styled-component via custom component通过自定义组件将 props 添加到 styled-component
【发布时间】:2021-09-25 22:39:20
【问题描述】:

当我将自定义组件与 Styled-component 一起使用时,我正在尝试传递一些道具。

这是我要关注的容器,我想通过props改变flex-direction:

const InputInnerContainer = styled.View`
  width: 100%;
  height: 42px;
  padding-horizontal: 5px;
  flex-direction: ${props => props.right ? "row-reverse": "row"};
  align-items: center;
  justify-content: space-between;
  border-radius: 4px;
  border-width: 1px;
  background-color: ${inputBackgroundColor};
  border: 2px solid ${inputBorderColor};
`;

这是我的自定义组件“输入”:

const Input = ({ onChangeText, icon, value, label,iconPosition}) => {
  return (
    <InputContainer>
      {label && <LabelText>{label}</LabelText>}
      <InputInnerContainer {...iconPosition}>
        <View>{icon && <LabelText>{icon}</LabelText>}</View>
        <InputField onChangeText={onChangeText} value={value} />
      </InputInnerContainer>
    </InputContainer>
  );
};

这就是我调用自定义组件的地方:

<Input
        label="Password"
        onChangeText={(text) => onChangeText(text)}
        value={value}
        icon="HIDE"
        iconPosition="right"
      />

我要传递的道具是“iconPosition”。但我不确定如何将它传递给 Styled-component。我对 Styled-component 还是比较陌生,所以欢迎提出任何想法。

【问题讨论】:

  • iconPosition 是一个字符串,所以就像&lt;InputInnerContainer iconPosition={iconPosition}&gt;一样转发它

标签: javascript reactjs react-native react-redux styled-components


【解决方案1】:

尝试不破坏它。不是这样:

<InputInnerContainer {...iconPosition}/>

但是这样:

<InputInnerContainer iconPosition={iconPosition}/>

您还需要更新样式组件:

const InputInnerContainer = styled.View`
  ...
  flex-direction: ${props => props.iconPosition === "right" ? "row-reverse" : "row"}
  ...
`

【讨论】:

  • 像魅力一样工作。谢谢,伙计们。
猜你喜欢
  • 2018-12-14
  • 2020-05-17
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 2019-06-14
  • 1970-01-01
相关资源
最近更新 更多