styled-components:样式化组件而不将它们包装在 containers/wrappers 中?

styled-components: Styling components without wrapping them in containers/wrappers?

是否可以在不创建容器的情况下设置 React 组件的样式?

这是我目前遇到的问题的一个例子。我总是需要将组件包装在 container/wrapper 中。像这样...

import React, { Component } from 'react';
import styled from 'styled-components';

const PitchSliderContainer = styled.input`
    text-align: right;
    float: right;
`;

const PitchSlider = () => <PitchSliderContainer
    type="range"
    min="0.9"
    max="1.1"
    step="any"
    onChange={this.props.onChange}
/>

export default PitchSlider;

有没有什么方法可以在不创建容器的情况下设置 PitchSlider 的样式?

我觉得你的做法是对的。因为这就是 Styled Components 的全部意义所在。创建可重复使用的 展示性 组件。在这里,您的 PitchSliderContainer 就是这样一个 input 组件。您可以编写一个更通用的组件来接受某些道具,并根据道具呈现 <input>。这样的样式组件当然也应该有一个名字吧

您所要求的可以通过其他方式完成。不推荐用于结构组件,但由于您的组件只有一个 <input> 标记,因此应该没问题:

const PitchSlider = ({ className }) => <PitchSliderContainer
    type="range"
    min="0.9"
    max="1.1"
    step="any"
    onChange={this.props.onChange}
    className={className}
/>

export default styled(PitchSlider)`
  text-align: right;
  float: right;
`;

确保您收到 className 作为 props 并将其传递给您的组件。

编辑:正如 Phil Pluckthun 所建议的,您也可以这样做:

const PitchSlider = styled.input.attrs({
  type: 'range',
  min: '0.9'
  max: '1.1'
  step: 'any'
  onChange: this.props.onChange
})`
  text-align: right;
  float: right;
`;

当您使用 styled 时,您用 HOC 包裹了您的初始容器。也就是说styled函数返回的只是一个可以正常使用的普通React组件,接收props而不一层额外的包裹。例如,它可以这样使用:

<ParentComponent>
  <PitchSliderContainer type='range' step='any' />
</ParentComponent>

查看 this 沙箱以查看您定义的最初在页面中使用的组件。