首页 > 解决方案 > 如何在 React 中重新分配 Ref 对象

问题描述

我正在尝试修复我无法控制他们如何使用 refs 的项目的一部分。目前有可编辑的文本元素通过使用 refs 和包含所有这些 refs 的组件中的状态变量来控制。我正在尝试实现一个取消按钮,它将已编辑的字段重置为其原始默认值。

我尝试使用打击代码来完成此操作,方法是将似乎存储在 ref.state.value 中的已编辑值替换为存储在 ref.props.defaultValue 中的原始值

this.state.refs 定义为

refs: Array<EditableText | null>;

可编辑文本:https ://blueprintjs.com/docs/#core/components/editable-text

带有引用的可编辑文本组件:

<EditableText
   disabled={!this.state.editingDesc}
   multiline={true}
   maxLines={10}
   defaultValue={description}
   ref={input =>
     (this.state.refs[index + 1] = input)
   }
/>

有错误的函数

public handleCancelBtn = () => {
    const newRefs = this.state.refs.map(ref => {
      if (ref != null) {
        const originalValue = ref.props.defaultValue;
        const newState = { ...ref.state, value: originalValue };
        const newRef = { ...ref, state: newState };
        return newRef;
      }
      return null;
    });
    this.setState({
      editingDesc: false,
      refs: newRefs
    });
  };

问题是编译器说我不能将 newRefs 分配给 ref 因为我缺少使它们成为编辑的文本元素的属性,例如渲染、componentDidMount 等。我不明白为什么扩展运算符没有处理从原始参考中复制所有内容。不过,我对 refs 了解不多,也找不到与此用例相关的文档。我真希望我可以重构整个组件以使用状态,遗憾的是我将不得不等待。如果有人可以给我一些帮助,我将不胜感激。谢谢你。

标签: reactjstypescript

解决方案


您可以尝试使用Object.assign()方法将可枚举和自己的属性从源对象复制到目标对象。看看Object.assign 文档Object.assign vs Object Spread

已编辑

public handleCancelBtn = () => {
    const newRefs = this.state.refs.map(ref => {
      if (ref != null) {
        let newRef = Object.assign({}, ref);
        newRef.state.value = ref.props.defaultValue;
        return newRef;
      }
      return null;
    });

    this.setState({
      editingDesc: false,
      refs: newRefs
    });
  };

推荐阅读