从外部样式化嵌套样式组件

Styling a nested styled-component from an outer one

使用 styled-components,我正在尝试设置我创建的嵌套 <Input /> 组件的样式,该组件在另一个组件中使用,该组件在键入时会出现一个下拉列表。我需要将 padding-left: 3rem 添加到此嵌套输入,但我无法从组件 <Dropdown />.

访问它
<Dropdown
  options={options}
/>

以上是我需要的地方导入的。我需要从上面的 <Dropdown />.

访问下面的输入
<div>
  <Input {...props}/> // I need to edit the padding in this component
  // rendered input unique to this new component would go here
</div>

上面的 <Input /> 是从另一个组件导入的,该组件在我需要输入的所有情况下都使用。

export const Dropdown = styled(DropDown)`
  padding-left: 3rem !important;
`;

该组件工作正常,但这不会影响我需要定位的输入的内部填充。

我该怎么办?

找到以下解决方案:

export const StyledInput = styled.div`
  && #id-for-input { // specifically on the <Input />
    padding-left: 3rem !important;
  }
`;


<StyledInput>
  <Dropdown />
</StyledInput>

根据您所说的,我建议填充 Input 组件的依赖性与您的 Dropdown 相关(您似乎已经意识到这一点)。

因此,您最好通过其中的包装样式组件将 "unqiue" 样式与您的 Dropdown 组件相结合。

以下示例很粗糙(绝不是完整的或有效的),但希望它说明了 padding-left 的所有权应该如何在 Dropdown 内而不是零星样式的浮动组件在您的代码库中的其他地方。

./Input/Input.jsx

const Input = ({ value }) => (
  <input value={value} />
);

./Dropdown/styled.js

const InputWrapper = styled.div`
  position: relative;
  padding-left: 3rem !important; /* Your padding */
`;

const Icon = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 3rem;
  height: 3rem;
  background: blue;
`;

const Menu = styled.ul`/* whatever */`;

./Dropdown/Dropdown.jsx

import Input from '...';
import { InputWrapper, Icon, Menu } from './styled';
const Dropdown = ({ options }) => (
  <div>
    <InputWrapper>
      <Icon />
      <Input value={'bleh'} />
    </InputWrapper>
    <Menu>{options}</Menu>
  </div>
);

此设置将推广可重复使用的 self-contained 组件。