You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中实现带变量下拉框的手动公式输入TextField?

React实现支持变量补全的公式输入TextField(基于Ant Design)

Ant Design的Select组件tags模式确实不适合这类场景——它更侧重预设标签的选择,无法灵活支持自由输入运算符和精准的变量插入。推荐用AutoComplete组件结合Input来实现,以下是具体实现方案:

核心思路

  • 监听输入框内容变化,实时从可用变量列表中匹配用户正在输入的片段,生成补全建议
  • 处理变量选择逻辑:将选中的变量插入到当前光标位置,而非替换整个输入内容
  • 完全放开输入限制,允许用户自由输入+、-、*、/、括号等运算符

代码实现

import { AutoComplete, Input } from 'antd';
import { useState, useRef } from 'react';

const FormulaInput = () => {
  const [value, setValue] = useState('');
  const [options, setOptions] = useState([]);
  const inputRef = useRef(null);
  // 自定义可用变量列表
  const availableVariables = ['Basic Fuel', 'Basic Kurs', 'Total Cost'];

  // 输入变化时生成匹配的补全选项
  const handleInputChange = (e) => {
    const inputValue = e.target.value;
    setValue(inputValue);

    // 提取用户正在输入的最后一段变量片段(跳过运算符、括号、空格)
    const lastInputSegment = inputValue.toLowerCase().split(/[+\-*/()\s]/).pop();
    // 匹配包含该片段的变量(不区分大小写)
    const matchedVariables = availableVariables.filter(variable => 
      variable.toLowerCase().includes(lastInputSegment)
    );

    setOptions(matchedVariables.map(varName => ({ value: varName })));
  };

  // 选择变量时插入到光标位置
  const handleVariableSelect = (selectedVar) => {
    const inputElement = inputRef.current;
    if (!inputElement) return;

    const { selectionStart: start, selectionEnd: end } = inputElement;
    const currentInputValue = inputElement.value;

    // 拼接新输入值:光标前内容 + 选中变量 + 光标后内容
    const newInputValue = `${currentInputValue.substring(0, start)}${selectedVar}${currentInputValue.substring(end)}`;
    setValue(newInputValue);

    // 光标自动移到插入变量的末尾
    setTimeout(() => {
      inputElement.selectionStart = inputElement.selectionEnd = start + selectedVar.length;
    }, 0);
  };

  return (
    <AutoComplete
      options={options}
      onSelect={handleVariableSelect}
      style={{ width: 400 }}
    >
      <Input
        ref={inputRef}
        value={value}
        onChange={handleInputChange}
        placeholder="输入公式,例如 (Basic Fuel + Basic Kurs)/Basic Fuel"
        allowClear
      />
    </AutoComplete>
  );
};

export default FormulaInput;

关键细节说明

  • 片段匹配逻辑:用正则/[+\-*/()\s]/分割输入内容,取最后一段作为匹配依据,确保用户输入运算符后,依然能正确匹配后续输入的变量
  • 光标位置处理:通过input的DOM引用获取当前光标位置,插入变量后自动将光标移到变量末尾,提升输入流畅度
  • 完全自由输入:Input组件未做任何输入限制,用户可随意输入运算符、括号等符号,补全建议仅作为辅助

扩展优化建议

  • 可以在AutoComplete的renderOption中自定义样式,给匹配的变量添加语法高亮
  • 增加公式合法性校验,比如检查括号是否配对、运算符使用是否合理
  • 支持变量的模糊匹配排序,优先显示更相关的变量

内容的提问来源于stack exchange,提问作者Nizar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:17:16