在 ContentEditable 组件数组中使用 useRef

时间:2021-01-17 10:32:44

标签: reactjs react-hooks contenteditable use-ref

我有一组 ContentEditable 组件,我想从中获取值并将其显示在它旁边的适当容器中。我的斗争是我认为我需要一个 useRef 数组来定位特定的 ContentEditable 组件并将正确的 e.target.value 设置为正确的 inputRef.current

https://codesandbox.io/s/blissful-bouman-bqpts?file=/src/InputList.jsx

1 个答案:

答案 0 :(得分:0)

您需要使用索引来处理多个状态:


const InputList = () => {
  const [finalValue, setFinalValue] = useState([]);
  const inputRef = useRef(["", "", "", "", ""]);

  const onChange = (i) => (e) => {
    inputRef.current[i] = e.target.value;
  };
  const onClick = (i) => () => {
    setFinalValue((prev) => [
      ...Object.assign(prev, { [i]: inputRef.current[i] })
    ]);
  };

  return (
    <div>
      {[...Array(5)].map((item, index) => {
        return (
          <Input
            key={index}
            onClick={onClick(index)}
            onChange={onChange(index)}
            html={inputRef.current[index]}
            finalValue={finalValue[index]}
          />
        );
      })}
    </div>
  );
};

https://codesandbox.io/s/priceless-mirzakhani-5pooz?file=/src/InputList.jsx:78-762

相关问题