简体   繁体   中英

onChange event fires on wrong mapped file input element

I am stuck on this issue with onChange handler being fired on a wrong element after .map function. I have a component, which I use to display mapped values, which looks like this:

const Step: React.FC<StepProps> = ({ status, title, text, onClick, onChange }) => {
  return (
    <button disabled={status === CompletionStatus.Completed} className={Styles.item} onClick={onClick}>
      <mui.IconButton css={css.completionIcon} disabled={status === CompletionStatus.Completed}>
        {status === CompletionStatus.Completed ? <muiIcons.Check /> : <Plus />}
      </mui.IconButton>

      <div className={Styles.content}>
        <span className={status === CompletionStatus.Completed ? Styles.titleCompleted : Styles.title}>{title}</span>

        <span className={status === CompletionStatus.Completed ? Styles.textCompleted : Styles.text}>{text}</span>
      </div>

      {onChange && (
        <>
          <label htmlFor="file-button" className={Styles.inputLabel} />
          <input id="file-button" className={Styles.input} type={'file'} onChange={onChange} />
        </>
      )}
    </button>
  );
};

So, some of the mapped elements are being used with onClick, and two use onChange to gain photos from the user.

The issue is, that every time I trigger the onChange event on any of those inputs, only the first ones fires, eg (I added this onChange function to test the name of the element that is being fired, and every time only the first one in the list is being console.logged)

onChange={(event: any)=> {
  console.log(event, step);
  event.target.value = null;
}}

So, I have figured out the issue here, maybe someone finds this helpful. Having input with type file only having one id (file-button) was causing only the first such input to work

<label htmlFor="file-button" className={Styles.inputLabel} />
<input id="file-button" className={Styles.input} type={'file'} onChange={onChange} />

The way I fixed this, was basically having that id property unique, so I passed an index to the component and changed the id to

id={`file-button-${index}`}

听起来您可能没有为映射函数中的每个项目设置一个key

{yourData.map((item, index) => <Component key={`item-${index}`} item={item} />)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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