【问题标题】:styled components : using css to add colour based on values样式化组件:使用 css 根据值添加颜色
【发布时间】:2020-04-19 13:56:22
【问题描述】:

我有一个看起来像这样的下拉组件

源代码:

const DropdownSelectPriority = props => {
  const { multiChoiceArray } = props
  return (
    <ButtonContainer>
      {multiChoiceArray.map(questionChoice => {
        return (
          <div key={questionChoice.id}>
            <p>{questionChoice.text}</p>
            <SimpleSelect
              placeholder="Select a priority"
              onValueChange={value => console.log(value)}
            >
              {questionChoice.options.map(options => {
                return <option value={options.label}>{options.value}</option>
              })}
            </SimpleSelect>
          </div>
        )
      })}
    </ButtonContainer>
  )
}

我想根据选择的值设置我的 div 样式,我该如何实现?例如,如果水质管理是最高优先级,我想添加一些样式等

【问题讨论】:

  • 您是否尝试阅读文档?这基本上是 styled-components 的主要特征
  • 是的,我做到了,但我不确定如何为每个 {options.value} 应用样式

标签: css reactjs oop ecmascript-6 styled-components


【解决方案1】:

只需使用 background 属性设置通用 Option 的样式:

const Select = styled.select`
  background: ${({ bg }) => bg};
`;

const Option = styled.option`
  background: ${({ bg }) => bg};
`;

const options = ['red', 'green', 'blue'];

const App = () => {
  const [selected, setSelected] = useState('red');
  return (
    <Select
      value={selected}
      onChange={e => setSelected(e.target.value)}
      bg={selected}
    >
      {options.map(option => (
        <Option key={option} value={option} bg={option}>
          {option}
        </Option>
      ))}
    </Select>
  );
};

【讨论】:

  • 嗯,不是我想要的...如果我希望 background: palevioletred; 是动态的而不是下拉项怎么办?
  • 所以给它添加一个状态
  • 为什么需要状态?在您的代码笔中,您没有使用{option} 的状态来使用动态颜色
  • 没必要,也可以用引用,从现在开始就不是styled-component问题了,就是react。
  • 我添加了一个带状态的示例
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 2019-10-31
  • 2010-09-11
  • 2023-02-16
相关资源
最近更新 更多