将占位符保持在 react-select

Keeping placeholder on react-select

我已经尝试了所有我能想到的方法,但我无法阻止 react-select 中的占位符消失(我假设已更改为 display: none 因为它不再位于 HTML) 当组件的值被 select 编辑时。

我已经通读了两篇有类似问题的帖子: https://github.com/JedWatson/react-select/issues/2152 https://github.com/JedWatson/react-select/issues/2143

但是还没有找到任何成功的方法

我在占位符元素上的样式是:

valueContainer: base => ({
        overflow: 'visible'
      }),
placeholder: (provided, state) => ({
        ...provided,
        position: "absolute",
        marginTop: '-30px',
        display: 
      state.isFocused || state.isSelected || state.selectProps.inputValue || state.value
      ? 'block'
      : 'block',
      }),

这里是 stackblitz。最终目标是在中心开始占位符并将其向上移动到焦点和 selection 上的位置。 问题是,一旦 selected,占位符就会消失。 https://stackblitz.com/edit/react-egf4va

您需要创建一个自定义的 ValueContainer,return 占位符在其中。然后在 属性 components 中传入 Select component:

import React, { Component } from 'react';

import { render } from 'react-dom';
import Select, {components} from 'react-select';
import Hello from './Hello';
import './style.css';
const { ValueContainer, Placeholder } = components;

const CustomValueContainer = ({ children, ...props }) => {
  return (
    <ValueContainer {...props}>
      <Placeholder {...props} isFocused={props.isFocused}>
        {props.selectProps.placeholder}
      </Placeholder>
      {React.Children.map(children, child =>
        child && child.type !== Placeholder ? child : null
      )}
    </ValueContainer>
  );
};
class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    const customStyles = {
      container: base => ({
        ...base,
        width: '100%',
      }),
      control: base => ({
        ...base,
        border: 0,
        // This line disable the blue border
        boxShadow: 'none',
        height: '42px',
        borderRadius: '6px'
      }),
      valueContainer: base => ({
        ...base,
        fontSize: '15px',
        top: '3.5px',
        marginLeft: '4px',
        overflow: 'visible'
      }),
      placeholder: base => ({
        ...base,
        fontStyle: 'italic',
        marginTop: '20px',
        position: 'absolute',
      })
    }
    const options = [
     { value: 'chocolate', label: 'Chocolate' },
     { value: 'strawberry', label: 'Strawberry' },
     { value: 'vanilla', label: 'Vanilla' }
   ];
    return (

      <div>
        <Select components={{ValueContainer: CustomValueContainer}}
        options={options} placeholder="Select" isClearable="true" styles={customStyles} className="react-select" classNamePrefix="react-select"/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));