保持对select的占位符

问题描述 投票:0回答:1

我尝试了所有我能想到的东西,但是当为组件选择一个值时,我无法防止react-select中的占位符消失(我假设已更改为display: none,因为它不再存在于HTML中。 >

我已经阅读了两篇类似的文章:https://github.com/JedWatson/react-select/issues/2152https://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',
      }),

这里是一堆突击。最终目标是从中心开始放置占位符,然后将其移至焦点和选择位置。问题是,一旦选择某项,占位符就会消失。https://stackblitz.com/edit/react-egf4va

我尽了我所能想到的一切,但是当值是...时,我无法防止react-select中的占位符消失(我假设已更改为display:none,因为它不再存在于HTML中)。]] >

您需要创建一个自定义ValueContainer,并在其中返回占位符。然后将其传递到Select

组件的属性components:
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'));
javascript css reactjs react-select react-state
1个回答
1
投票

您需要创建一个自定义ValueContainer,并在其中返回占位符。然后将其传递到Select

© www.soinside.com 2019 - 2024. All rights reserved.