使用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;
`;
该组件工作正常,但这不能影响我需要针对的输入的内部填充。
我做什么好?
发布于 2019-01-08 22:48:25
根据您所说的,我建议填充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
组件。
发布于 2019-01-08 17:32:11
解决方案如下:
export const StyledInput = styled.div`
&& #id-for-input { // specifically on the <Input />
padding-left: 3rem !important;
}
`;
<StyledInput>
<Dropdown />
</StyledInput>
https://stackoverflow.com/questions/54096206
复制