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

NextJS 如何不渲染表单字段但在提交动作/事件中仍传递对应值

解决方案

你可以直接从组件已有的card状态中读取ownedBy字段,无需将该字段渲染到表单DOM中,完全规避用户通过审查元素看到字段的问题,修改步骤如下:

  • 调整card状态的初始值为对象,避免读取属性时报错
  • 删除表单内的隐藏ownedBy输入框代码
  • 修改PATCH请求的参数取值逻辑,直接从card状态中拿ownedBy值,无需从表单元素读取

修改后的核心代码示例:

// 调整state初始值为对象
const [card, setCard] = useState({});

const submitCard = async event => {
  event.preventDefault()
  const res = cardId ? await fetch(
    '/api/cards/'+cardId,
    {
      body: JSON.stringify({
        cardText: event.target.cardText.value,
        category: event.target.category.value,
        cardUsers: event.target.cardUsers.value,
        source: event.target.source.value,
        // 直接从state取原数组类型的ownedBy,不需要额外做字符串拆分
        ownedBy: card.ownedBy || [],
      }),
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'PATCH'
    }
  ) : await fetch(
    '/api/cards/insertCard',
    {
      body: JSON.stringify({
        cardText: event.target.cardText.value,
        category: event.target.category.value,
        cardUsers: event.target.cardUsers.value,
        source: event.target.source.value
      }),
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }
  )
  alert("Card Submitted");
} 

// return内的表单直接删除原有隐藏的ownedBy输入框即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:39:01