Antd Select组件上的自定义文本框
P粉790187507
P粉790187507 2024-03-30 11:16:20
[React讨论组]

如果用户认为适合的选择不在“选择”选项中显示的选项中,我想让用户能够添加自定义文本。我已经成功创建了自定义文本字段,但是获取用户输入并将其设置为选择组件的值变得很痛苦(听起来很容易做到,但由于某种原因它不工作) 这是我的实现

const [selectedpurpose, setSelectedPurpose] = useState("");// selected value of the select component
  const [customOption, setCustomOption] = useState("");//custom userinput
  
   const [dropoptions, setDropOptions] = useState([
{ value: "General Meeting", label: "General Meeting" },
{ value: "Consultation Meeting", label: "Consultation Meeting" },
{ value: "AdCampaign Meeting", label: "Ad Campaign Meeting" },
{ value: "Marketing Meeting", label: "Marketing Meeting" },
 ]);//select options

 // function to recored custom user input
 const handleAddOption = () => {
  if (customOption) {
  const newOption = { value: customOption, label: customOption };
  setDropOptions([newOption, ...dropoptions]);
  setSelectedPurpose(customOption);
  setCustomOption("");
 }
 };
    
   //my form
   
           {
                      if (e.target.value.length > 20) {
                        // if user has reached the maximum length
                        // show a message or change the color of the input to indicate the limit has been reached
                        // for example:
                        openNotificationWithIcon(
                          "error",
                          "Warning",
                          "Maximum length reached!"
                        );
                      } else {
                        setCustomOption(e.target.value);
                      }
                    }}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        handleAddOption();
                      }
                    }}
                  />
                  
                
)} > {dropoptions.map((option) => ( ))}

我做错了什么,根据我的代码,单击添加按钮按钮并按 Enter 键应该将新值添加到选项数组中,并选择用户输入作为选择组件的值,但到目前为止它只会将其添加到选项数组并忽略将其设置为选择值 感谢任何帮助

1
0
0
P粉790187507
P粉790187507

全部回复(1)
P粉808697471
try this one   
    
     import React from "react";
        import "./styles.css";
        import Select, { components } from "react-select";
        
        const CustomInput = (props) => {
          const { maxLength } = props.selectProps;
          const inputProps = { ...props, maxLength };
        
          return ;
        };
        
        const App = () => {
          const options = [
            { label: "Option 1", value: 1 },
            { label: "Option 2", value: 2 },
            { label: "Option 3", value: 3 }
          ];
        
          return (
            
          );
        };
        
        export default App;
专题推荐
更多>
热门话题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号