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

react-mentions使用异常:输入@未触发用户名联想功能

问题排查与修复方案

核心问题分析

  • 用户数据未正确传递:getUsers仅发起请求但未返回/存储用户数据,还直接将函数传给<Mention>的data属性(data需要接收用户数组而非函数)。
  • 组件嵌套错误:把自定义Mentions组件嵌套在普通<Textarea>内,react-mentions的<MentionsInput>本身是独立输入组件,不能这样嵌套。
  • 状态管理缺失:未用状态存储获取到的用户列表,无法为联想功能提供数据源。

修复后的Mentions组件代码

import { useState, useEffect } from 'react';
import { MentionsInput, Mention } from 'react-mentions';
import { Box } from '@mui/material'; // 按实际UI库调整

const defaultStyle = {
  border: '1px solid #ddd',
  borderRadius: '4px',
  padding: '8px',
  fontSize: '14px'
};

const defaultMentionStyle = {
  backgroundColor: '#e8f4fd',
  padding: '2px 4px',
  borderRadius: '3px'
};

const Mentions = ({ value, onChange }) => {
  const [users, setUsers] = useState([]);
  const showToast = useShowToast();

  useEffect(() => {
    const getUsers = async () => {
      try {
        const res = await fetch(`http://localhost:5000/api/users/users`);
        const data = await res.json();
        if (data.error) {
          showToast("错误", data.error, "error");
          return;
        }
        // 转换为react-mentions要求的格式:每个项需包含id和display字段
        const formattedUsers = data.map(user => ({
          id: user.username, // 按后端返回的实际字段调整
          display: user.username
        }));
        setUsers(formattedUsers);
      } catch (error) {
        showToast("错误", error.message, "error");
        console.error(error);
      }
    };
    getUsers();
  }, [showToast]);

  return (
    <Box>
      <MentionsInput
        style={defaultStyle}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        allySuggestionsListLabel="推荐提及用户"
      >
        <Mention
          style={defaultMentionStyle}
          trigger="@" // 明确指定触发联想的字符
          data={users} // 传入格式化后的用户数组
        />
      </MentionsInput>
    </Box>
  );
};

export default Mentions;

修复CreatePost组件的使用方式

移除原普通<Textarea>,直接使用修复后的Mentions组件:

// CreatePost组件内
const [postText, setPostText] = useState("");

const handleTextChange = (newValue) => {
  setPostText(newValue);
};

// 替换原Textarea代码
return (
  // ...其他组件内容
  <Mentions value={postText} onChange={handleTextChange} />
  // ...其他组件内容
);

关键修复点说明

  • 用户数据处理:用useEffect在组件挂载时请求数据,将返回结果格式化为react-mentions要求的结构并存入状态。
  • 触发字符配置:给<Mention>添加trigger="@"属性,明确触发联想的字符。
  • 组件正确使用:react-mentions的<MentionsInput>是独立输入组件,不能嵌套在普通<Textarea>中,直接通过props与父组件状态同步即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:52:42