我已经尝试了所有我能想到的方法,但是我无法阻止 react-select 中的占位符消失(我假设更改为 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',
}),
这是一个堆栈 Blitz 。最终目标是在中心开始占位符并将其移动到焦点和选择的位置。 问题是,一旦选择了某些东西,占位符就会消失。 https://stackblitz.com/edit/react-egf4va
最佳答案
您需要创建一个自定义的 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 - 在 react 选择上保留占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61895814/