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

React Native Gifted Chat自定义视图条件渲染异常问题

问题分析与解决方案

核心问题是你用了全局状态isSchedule控制按钮显示,当状态变为true时,所有消息的自定义视图都会渲染按钮,包括用户发送的消息。正确的做法是把按钮显示条件绑定到单条消息的专属属性,而非全局状态。

步骤1:修改消息结构,给目标消息添加专属标记

在创建机器人消息时,直接给需要显示按钮的消息添加自定义字段(比如showScheduleButton),替代全局状态:

try {
  const response = ...;
  if (response) {
    const isScheduleMsg = response.data.reply.substring(0,8).toLowerCase() === "schedule";
    const botMessage = {
      _id: ...,
      text: response.data.reply.trim(),
      createdAt: new Date(),
      user: {
        _id: 1,
        name: 'Chatbot',
        avatar: 'https://img.freepik.com/premium-vector/robot-icon-bot-sign-design-chatbot-symbol-concept-voice-support-service-bot-online-support-bot-vector-stock-illustration_100456-34.jpg'
      },
      pending: true,
      // 添加专属标记,仅当前消息生效
      showScheduleButton: isScheduleMsg
    };

    botSend([botMessage]);
  }
} catch (error) {
  console.error("Error in sending message: " + error);
}

步骤2:重写renderCustomView,针对单条消息判断

renderCustomView的参数包含当前消息对象,你需要接收这个参数,然后判断是否要渲染按钮:

// 替换原来的pressButton函数
const renderCustomView = useCallback(({ message }) => {
  // 仅当消息是机器人发送的,且标记为需要显示按钮时才渲染
  if (message.user._id === 1 && message.showScheduleButton) {
    return (
      <TouchableOpacity style={styles.buttonStyle} onPress={pressedMessage}>
        <LinearGradient
          colors={['purple','white']}
          style={styles.gradientButton}
          start={{x: 0, y: 0}}
          end={{x: 1, y: 0}}  
        >
          <Text>Press this to add to calendar!</Text>
        </LinearGradient>
      </TouchableOpacity>
    );
  }
  // 不符合条件时返回null,不渲染任何内容
  return null;
}, []); // 依赖项按需添加,比如pressedMessage如果是外部函数需要加入

步骤3:更新GiftedChat组件配置

把原来的renderCustomView={pressButton}替换为新的renderCustomView={renderCustomView}:

<GiftedChat
  messages={messages}
  showAvatarForEveryMessage={true}
  onSend={messages=> onSend(messages)}
  placeholder="Type your message..."
  renderBubble={renderBubble}
  user={{
    _id: auth()?.currentUser?.uid!,
  }} 
  renderCustomView={renderCustomView}
  isCustomViewBottom={true}
/>

为什么之前的方法无效?

  • 全局状态isSchedule会影响所有消息:当你设置isSchedule=true后,所有消息的自定义视图都会触发渲染,包括用户消息。
  • 原来的pressButton函数没有接收当前消息参数,无法区分是哪条消息要渲染按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:32:47