首页 > 其他 > 详细

如何使用 React createRef

时间:2020-06-11 14:23:47      阅读:28      评论:0      收藏:0      [点我收藏+]

React 提供三种方式创建 Refs:

  1. 字符串 Refs (将被废弃)
  2. 回调函数 Refs
  3. React.createRef (从React 16.3开始)

第一种方式不推荐使用,原因在此, 并且可能会在之后的版本移除。

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.toggleInputCase = this.toggleInputCase.bind(this);
    this.state = { uppercase: false };
  }
  
  toggleInputCase() {
    const isUpper = this.state.uppercase;
    const value = this.refs.inputField.value;
    
    this.refs.inputField.value =
      isUpper
        ? value.toLowerCase()
        : value.toUpperCase();
        
    this.setState({ uppercase: !isUpper });
  }

  render() {
    return (
      <div>
        {/* 创建一个字符串 ref: inputField */}
        <input type="text" ref="inputField" />
        
        <button type="button" onClick={this.toggleInputCase}>
          Toggle Case
        </button>
      </div>
    );
  }
  
}

 

第二种方式是

    return (
      <div>
        {/* Creating a callback ref and storing it in this.inputField */}
        <input type="text" ref={elem => this.inputField = elem} />
        
        <button type="button" onClick={this.toggleInputCase}>
          Toggle Case
        </button>
      </div>
    );

 

第三种方式 React.createRef

    return (
      <div>
        {/* Referencing the ref from this.inputField */}
        <input type="text" ref={this.inputField} />
        
        <button type="button" onClick={this.toggleInputCase}>
          Toggle Case
        </button>
      </div>
    );


原文 https://zhuanlan.zhihu.com/p/64412949

如何使用 React createRef

原文:https://www.cnblogs.com/chenzxl/p/13092346.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!