【问题标题】:useRef in an array of ContentEditable components在 ContentEditable 组件数组中的 useRef
【发布时间】:2021-01-17 10:32:44
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs react-hooks contenteditable use-ref


    【解决方案1】:

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

    
    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

    【讨论】:

    • 谢谢!这解决了我的头痛!我还补充说,如果输入组件的长度会发生变化,同时保持输入列表而不是 [...Array()] const inputRef = useRef(new Array(inputs.length).fill("")); useEffect(() =&gt; { if (inputRef.current.length !== inputs.length) { inputRef.current.push( ...new Array(inputs.length - inputRef.current.length).fill("") ); } }, [inputs.length]);
    猜你喜欢
    • 2022-11-21
    • 2021-10-23
    • 2021-07-22
    • 2021-12-15
    • 2020-07-26
    • 2020-02-08
    • 2020-04-27
    • 2022-01-10
    • 2020-06-18
    相关资源
    最近更新 更多