【实战】React 实战项目常见报错 —— 直接使用 ref, 报错:react can not set ref string for ...


一、问题

react 中直接使用 ref, 报错:

react can not set ref string for ...

二、解决

1.React.createRef()

constructor() {
    
    
    super();
    this.refObj = React.createRef()
}

let refDom = this.refObj.current
let refDomValue = this.refObj.current.value
<div ref={
     
      this.refObj }>

2.回调函数

constructor() {
    
    
    super();
    this.refObj = null;
    this.setRefObj = refObj =>{
    
    
        this.refObj = refObj ;
    }
}

let refDom = this.refObj.value
<div ref={this.setRefObj } ></div>


三、拓展学习

1.React.refs

Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。

Refs 是一种非常特殊的属性,你可以用来绑定到 render() 输出的任何组件上去。这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在 任何时间 总是拿到正确的实例。

应用场景:

  • 管理焦点,文本选择或媒体播放。
  • 触发强制动画。
  • 集成第三方 DOM 库。

(1)创建 Refs

React.createRef()

React 16.3 版本引入 React.createRef() API

class MyComponent extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    
    
    return <div ref={
    
    this.myRef} />;
  }
}

创建 Refs 分为两步:

  • 在构造函数中通过 React.createRef() API 声明 refs 并 将其设定为 整个组件的一个实例属性,以便在整个组件中使用,甚至传递出去
  • 在 render 函数中绑定 DOM 元素

(2)访问 Refs

const node = this.myRef.current;

ref 的值根据绑定DOM节点的类型而有所不同:

  • 当 ref 属性用于 原生 DOM 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
  • 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例(实例化的组件)作为其 current 属性。

注意:

  • 不能在 函数组件 上使用 ref 属性,因为函数组件没有实例
  • 为 DOM 元素添加 ref
class CustomTextInput extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    
    
    // 直接使用原生 API 使 text 输入框获得焦点
    this.textInput.current.focus();
  }

  render() {
    
    
    return (
      <div>
        <input type="text" ref={
    
    this.textInput} />
        <input type="button" value="Focus the text input" onClick={
    
    this.focusTextInput}
        />
      </div>
    );
  }
}
  • 为 class 组件添加 Ref
class AutoFocusTextInput extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.textInput = React.createRef();
  }

  componentDidMount() {
    
    
  	// 这里在父组件加载时,自动调用子组件中的方法,使 text 输入框获得焦点
    this.textInput.current.focusTextInput();
  }

  render() {
    
    
    return (
      <CustomTextInput ref={
    
    this.textInput} />
    );
  }
}

以上部分描述及案例来自:Refs and the DOM – React

react 16.3 之前版本使用方式:

猜你喜欢

转载自blog.csdn.net/qq_32682301/article/details/128791032