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

React中使用Props生成HTML ID失败问题求助(附代码)

我来帮你解决这个props拼接生成id的问题~

问题根源

你现在控制台输出NaN的核心原因是错误地访问了props的属性:
看你的ItemContainer.js,给Item组件传的title和name都是直接的字符串值(比如<Item title='' name="6 inch" />),但在Item.js里你却写成了this.props.title.value和this.props.name.value——字符串本身没有value属性,所以这两个值都会变成undefined,undefined + undefined就会得到NaN。

修复方案

1. 正确读取props值

直接使用this.props.title和this.props.name(它们本身就是字符串)来拼接id,同时注意给input的id绑定变量时要用大括号包裹。

2. 优化id格式(可选但推荐)

为了让id更符合HTML规范(避免空格),可以用模板字符串加分隔符,或者把空格替换成下划线/连字符。

3. 传递分类title(后续扩展用)

你之前给Item传的title是空字符串,其实可以把ItemContainer的分类title(比如"Wraps"、"Bonnets")传下去,这样拼接的id会更有辨识度。

修改后的代码示例

第一步:更新ItemContainer.js,传递分类title

import React from 'react';
import Item from './Item';
import PropTypes from 'prop-types';

export default class ItemContainer extends React.Component {
  render() {
    if (this.props.title === 'Wraps') {
      return (
        <div>
          <h3>{this.props.title}</h3>
          {/* 把当前容器的title传给Item */}
          <Item title={this.props.title} name="6 inch" />
          <Item title={this.props.title} name="8 inch"/>
          <Item title={this.props.title} name="10 inch"/>
          <Item title={this.props.title} name="12 inch"/>
          <Item title={this.props.title} name="Cocoon"/>
        </div>
      )} else {
        return (
          <div>
            <h3>{this.props.title}</h3>
            <Item title={this.props.title} name="Tiny"/>
            <Item title={this.props.title} name="Preemie"/>
            <Item title={this.props.title} name="Micro"/>
            <Item title={this.props.title} name="New Born"/>
          </div>
        )
      }
    }
}

第二步:修复Item.js的id拼接逻辑

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ItemContainer from './ItemContainer';

export default class Item extends React.Component {
  render() {
    // 用模板字符串拼接,替换空格为连字符,生成合法id
    let var_id = `${this.props.title.replace(/\s+/g, '-')}-${this.props.name.replace(/\s+/g, '-')}`;
    console.log(var_id); // 现在会输出类似"Wraps-6-inch"的合法字符串
    return (
      <div style={{display: "flex"}}>
        <p>
          {this.props.name}
          {/* 用大括号绑定变量作为id */}
          <input id={var_id} type="number" />
        </p>
      </div>
    )
  }
}

这样修改后,你就能得到像Wraps-6-inch、Bonnets-Preemie这类清晰且合法的HTML id了,后续扩展gender分类时,只需要在props里新增gender参数,再加入拼接逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:07:52