我已经试过各种我能想到的,但我不能防止占位符在从消失发生反应-选择(I假设变更为display: none
,因为它不再在HTML)时被选择用于一个值组件。
我已经阅读了两篇类似的文章: 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',
}),
这是一次突击。最终目标是从中心开始放置占位符,然后将其移至焦点和选择位置。 问题是,一旦选择某项,占位符就会消失。 https://stackblitz.com/edit/react-egf4va
答案 0 :(得分:4)
您需要创建一个自定义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'));