如何在react-select中添加浮动标签?

3
我正在尝试使用MaterialUI主题构建Web应用程序,并且需要使用自动完成。原来MUI V2没有AutoComplete并且文档建议使用替代方案。React-select拥有我需要的所有功能,但我无法弄清楚如何使其看起来类似于其他控件-特别是如何在用户开始输入或单击下拉列表时使浮动标签浮动。
我的做法如下:
  • 创建一个组件(IntegratedSelect),该组件使用自react-select中的此Demo中的代码
  • 此文件克隆到CustomAutocomplete.jsx并将替换为
  • 修改代码以将id传递给IntegratedSelect并将该ID设置为Select控件
我还尝试了许多不同的方法(如设置refs、使用@material/react-floating-label中的FloatingLabel等),但都没有成功。
请问如何触发标签的浮动,或者如何将react-select控件与浮动标签连接起来?
谢谢你的帮助!
致敬, VB
附注: 添加了Gist:https://gist.github.com/mspclaims/e07bf1ff657fa8eb4756bc0514a164fe

1
你能分享相关的代码吗? - Anas
我更新了帖子,包括源代码和截图的链接。谢谢关注! - vba66a
1个回答

4

根据 GitHub 上类似问题的 这个注释,我成功解决了它!在我的情况下,我使用了 styled-component,但不管使用什么样式,它都应该可以工作。

import React from "react";
import styled from "styled-components";
import { components } from "react-select";

export const Control = (props: any) => {
  return (
    <>
      <Label isFloating={props.isFocused || props.hasValue}>Select</Label>
      <components.Control {...props} />
    </>
  );
};

const Label = styled.label<{ isFloating?: boolean }>`
  left: 10px;
  pointer-events: none;
  position: absolute;
  transition: 0.2s ease all;
  -moz-transition: 0.2s ease all;
  -webkit-transition: 0.2s ease all;
  z-index: 1;

  top: ${(props) => (props.isFloating ? `5px` : `35%`)};
  font-size: ${(props) => (props.isFloating ? `0.5rem` : `1rem`)};
`;

您可以将自定义控件组件添加到Select中:
<Select 
  ...
  components={{ Control }} 
  placeholder=""
/>

注意:您必须确保您的选择组件没有空的默认值,否则hasValue将始终为true。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接