【问题标题】:How can I add floating label to react-select?如何将浮动标签添加到反应选择?
【发布时间】:2023-03-22 11:54:01
【问题描述】:

我正在尝试使用 MaterialUI theme 构建 Web 应用程序,我需要使用自动完成功能。事实证明 MUI v2 没有自动完成功能,文档建议使用替代方案。 react-select 具有我需要的所有功能-但我无法弄清楚如何使其看起来与其他控件相似-特别是如何使浮动标签在用户开始输入或单击下拉菜单时浮动。

我做了什么:

  • 创建了一个组件 (IntegratedSelect),它使用来自 this demo 的 react-select
  • this file 克隆到CustomAutocomplete.jsx 并用<IntegratedSelect> 替换<Input>
  • 修改代码以将 id 传递给 IntegratedSelect 并将该 id 设置为 Select 控件

.. 并尝试了许多不同的其他方法(设置 refs,使用 @material/react-floating-label 中的 FloatingLabel 等).. 没有运气。

你能告诉我如何触发标签上的浮动,或者用浮动标签连接反应选择控件吗? 任何帮助将不胜感激!

问候, VB


附:要点补充:https://gist.github.com/mspclaims/e07bf1ff657fa8eb4756bc0514a164fe

【问题讨论】:

  • 可以分享相关代码吗?
  • 我更新了帖子以包含指向源代码和屏幕截图的要点链接。感谢收看!

标签: reactjs material-ui react-select


【解决方案1】:

this comment 关注 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=""
/>

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

【讨论】:

    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2022-01-14
    相关资源
    最近更新 更多