如何在ReactJS中使用默认值编辑输入

时间:2020-10-13 08:09:03

标签: reactjs react-native

因此,除了将value更改为defaultValue来手动更改输入值之外,还有其他方法吗? (当使用defaultValue时,我的程序无法正常运行)

ChildComponent = React.memo(
  ({ name, index, onChange, onDelete
  }) => {
    return (
      <div>
        <input value={name} onChange={onChange(index, name)} />
        <button onClick = {() => onDelete(index)}>delete</button>
      </div>
    );
  }
);
 function App() {
  const [names, setNames] = React.useState(["First", "Second"]);
  const newName = React.useRef();

  const onNameChange = (index: number, newName: string) => (event: {
    target: { value: string };
  }) => {
    names[index] = event.target.value;
    setNames(names);
  };
  function onNameDelete(index: number) {
    const nameArr = [...names];
    nameArr.splice(index, 1);
    setNames(nameArr);
  }
  return (
    <div>
      {names.map((name, index) => (
        <ChildComponent
          key={index}
          name={name}
          index={index}
          onChange={onNameChange}
          onDelete={onNameDelete}
        />
      ))}
    </div>
  );
}

1 个答案:

答案 0 :(得分:1)

问题出在onChange中的ChildComponent输入处理程序中。您根本没有使用用户传递的值来输入。您需要将其编写为类似于onDelete处理程序(使用存储在event.target.value中的代码段中的新值):

ChildComponent = React.memo(
  ({ name, index, onChange, onDelete
  }) => {
    return (
      <div>
        <input value={name} onChange={(event) => onChange(index, event.target.value)} />
        <button onClick = {() => onDelete(index)}>delete</button>
      </div>
    );
  }
);

还要查看Html documentation中输入更改处理程序的定义。

编辑: 另一个问题是您在父控制器中的处理程序:

 const onNameChange = (index: number, newName: string) => (event: {
    target: { value: string };
  }) => {
    names[index] = event.target.value; //this is BAD, do not change your state value directly, moreover, the event is undefined here
    setNames(names);
  };

您需要不可变地更新数组中的项(源Updating an Item in an Array):

const onNameChange = (index: number, newName: string) => (event: {
  target: { value: string };
}) => {
  const newNames = names.map((item, itemIndex) => {
    if (itemIndex !== index) {
      // This isn't the item we care about - keep it as-is
      return item
    }

    // Otherwise, this is the one we want - return an updated value
    return newName;
  });
  setNames(newNames);
};
相关问题