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

React中获取Test组件索引问题:key值返回对象如何处理

解决React组件获取索引的问题

你的问题出在两个关键点:

  1. React组件的参数是单个props对象,不是分开的inputs和key,你现在打印的key其实是组件的上下文参数,和你设置的key属性完全无关。
  2. React的key属性是给框架内部用来识别列表元素的,不会自动传递给组件作为props,要获取索引得手动把它作为props传进去。

修改后的代码:

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";

function App() {
  const [component, setComponent] = useState([]);

  // 正确接收props对象,解构出需要的inputs和index
  const Test = observer(({ inputs, index }) => {
    console.log(inputs);
    console.log(index); // 现在这里能拿到正确的索引了
    return (
      <div>
        <p>Test {index} </p>
      </div>
    );
  });

  return (
    <div>
      {component.map((Input, index) => (
        // 手动把index作为props传给组件,key保留给React内部使用
        <Input inputs={component} key={index} index={index} />
      ))}
      <button onClick={() => setComponent([...component, Test])}>
        Click me
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

额外提示:

  • 你原来的空useEffect可以直接删掉,否则会触发React的依赖警告。
  • 把组件存在state里的写法不太常规,通常建议把需要渲染的数据存在state,然后统一渲染Test组件(比如component.map((item, index) => <Test key={index} index={index} />)),这样代码逻辑会更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:16:38