如何在React-Select输入中添加永久标签?

时间:2018-01-08 20:41:18

标签: react-select

如何扩展React Select以在输入中永久显示输入标签?这是一个粗略的模型:Mockup

注意,我不想使用'占位符'道具,因为我希望即使在设置了值之后也会显示此标签。

1 个答案:

答案 0 :(得分:1)

您可以通过将placeholder设置为空值并在CSS中创建伪:before元素来实现:

class App extends React.Component {
  state = {
    value: [],
  }
  handleChange = (value) => {
    this.setState({ value });
  }
  render() {
    return (
      <Select
        className="my-react-select"
        multi
        onChange={this.handleChange}
        options={[
          { value: 'caramel',   label: 'Caramel' },
          { value: 'chocolate', label: 'Chocolate' },
          { value: 'vanilla',   label: 'Vanilla' },
          { value: 'mudcake',   label: 'Mudcake' },
        ]}
        placeholder=""
        value={this.state.value}
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
#root {
  font-family: sans-serif;
  max-width: 400px;
}

.my-react-select .Select-control:before {
  color: #aaa;
  content: 'Flavors';
  line-height: 34px;
  padding-left: 10px;
  padding-right: 10px;
  position: absolute;
}

.my-react-select .Select-placeholder + .Select-input,
.my-react-select .Select-input:first-child,
.my-react-select .Select-value:first-child {
  margin-left: 70px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<script src="https://unpkg.com/prop-types@15.5.10/prop-types.js"></script>
<script src="https://unpkg.com/classnames@2.2.5/index.js"></script>
<script src="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select/dist/react-select.js"></script>

<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">

<div id="root"></div>