英文:
Does React make sure an element id stays unique?
问题
在项目中多次使用这些组件时,即使我们明确设置了id = "brandName",id属性保持唯一的原因是因为React会为每个组件的实例创建一个独立的虚拟DOM。虽然你在多个组件中设置了相同的id,但这些id实际上是在不同的虚拟DOM节点上使用的,因此不会导致相同的id出现在实际渲染的HTML中。这是React在内部处理的一部分,确保DOM的正确性。
换句话说,React在构建实际的DOM元素时,会确保id是唯一的,即使你在多个组件中使用相同的id。这是React的一个关键特性,它通过虚拟DOM的机制来管理和确保DOM的一致性。
英文:
Lets stay we have two components: ItemForm and Inpunt . I am passing label and id props to Input, :
const ItemForm = () => {
  return (
    <form>
      <Input
        label= "Name:"
        input={{
          id: "brandName",
          type: "text"
        }}
      />
    </form>
  );
};
And here we have the Input component:
const Input = (props) => {
  return (
    <div>
      <label htmlFor={props.input.id}>{props.label}</label>
      <input {...props.input} />
    </div>
  );
};
My question is: when we use these components multiple times in a project, how does the id prop remains unique, even when we are explicitly saying that id = "brandName" ? (similar to writing plain html when we can't have more than one instance of an id.)
PS : It works when I use these components, but I want to know WHY and HOW it works under the hood!
答案1
得分: 0
不仅如此(只需连续两次使用相同id的<Input>)。
一个可能的解决方案是在id后附加一个唯一标识符,以确保它是唯一的:
import { nanoid } from "nanoid";
function getId(id) {
  return `${id}_${nanoid()}`;
}
const Input = ({ input, label }) => {
  const id = getId(input.id);
  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input {...input} id={id} />
    </div>
  );
};
我在这个示例中使用了nanoid。
英文:
It doesn't (just use <Input> twice in a row with the same id).
A possible solution is to append a unique identifier to the id to make sure it is unique:
import { nanoid } from "nanoid";
function getId(id) {
  return `${id}_${nanoid()}`;
}
const Input = ({ input, label }) => {
  const id = getId(input.id);
  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input {...input} id={id} />
    </div>
  );
};
I used nanoid for this example.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论