样式化的组件:使用CSS根据值添加颜色

时间:2019-12-30 21:57:16

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

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

enter image description here

源代码:

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的样式,如何实现呢?例如,如果水质管理是重中之重,我想添加一些样式等

1 个答案:

答案 0 :(得分:1)

只需使用背景属性设置通用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>
  );
};

Edit boring-hypatia-d16c1