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

如何将React Native TextInput拆分的标签转为key:true格式用于POST请求

实现代码

你可以通过数组的reduce方法完成转换,同时增加空格清理、空标签过滤逻辑兼容异常输入场景,修改后的代码如下:

const handleTags = (e: string) => {
  // 拆分标签并做格式清洗
  const validTags = e.split(',')
    .map(tag => tag.trim()) // 移除单个标签首尾空格
    .filter(tag => tag); // 过滤空标签,兼容多逗号、首尾逗号场景

  // 转换为要求的对象格式
  const postTagParams = validTags.reduce((prev, tag) => {
    prev[tag] = true;
    return prev;
  }, {} as Record<string, boolean>);

  // 此处直接将postTagParams作为POST参数提交即可
  console.log(postTagParams);
}

<TextInput placeholder="Tags" onChangeText={handleTags} />

效果验证

当你在输入框输入android,samsung,phone时,最终得到的postTagParams就是你需要的结构:

{
  "android": true,
  "samsung": true,
  "phone": true
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 03:36:06