简体   繁体   English

React htmlFor - 点击 label 关注输入错误

[英]React htmlFor - clicking label focus on the wrong input

I have the following code:我有以下代码:

const SomeComponent = () => {
return (
    <div>
            <label className={styles.label} htmlFor="firstName">
              First Name
            </label>
            <input type="text" id="firstName" value={user.firstName} />
          </div>
          <div>
            <label className={styles.label} htmlFor="lastName">
              Last Name
            </label>
            <input type="text" id="lastName" value={user.lastName} />
          </div>
          <div>
            <label className={styles.label} htmlFor="email">
              Email
            </label>
            <input type="email" id="email" value={user.email} />
          </div>);
    }

which is rendered in multiple places on the same page.它在同一页面上的多个位置呈现。 Clicking on the label of an element in the middle always creates focus on the first input, and not the input near it.单击中间元素的 label 始终会在第一个输入上创建焦点,而不是在它附近的输入上。

How I can make sure the label focuses on the right input (The one near it, which is in the same component) and not the first one (the first SomeComponent which was rendered)?我如何确保 label 专注于正确的输入(靠近它的那个,它在同一个组件中)而不是第一个(渲染的第一个SomeComponent )?

You have to make sure that ids are unique across the whole page.您必须确保 id 在整个页面中是唯一的。 So looks like you have several inputs using the id email And that is why the first input in the page gets the focus.所以看起来你有几个输入使用 id email这就是页面中的第一个输入获得焦点的原因。

One way to fix it would be to pass the id To the component as props.解决它的一种方法是将id作为道具传递给组件。


const SomeComponent = ({id}) => {
  
  return (
    <div>
            <label className={styles.label} htmlFor={`firstName-${id}`}>
              First Name
            </label>
            <input type="text" id= {`firstName-${id}`} value={user.firstName} />
          </div>
          <div>
            <label className={styles.label} htmlFor= {`lastName-${id}`} >
              Last Name
            </label>
            <input type="text" id= {`lastName-${id}`} value={user.lastName} />
          </div>
          <div>
            <label className={styles.label} htmlFor= {`email-${id}`} >
              Email
            </label>
            <input type="email" id= {`email-${id}`} value={user.email} />
          </div>);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM