Deprecation warning using this.refs

后端 未结 3 1618
忘了有多久
忘了有多久 2020-11-27 06:16

I have a React component and I want to toggle a css class when clicked.

So I have this:

export class myComponent extends React.Component {
  construc         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 06:59

    The Lint rule you are referring to is called no-string-refs and warns you with:

    "Using string literals in ref attributes is deprecated (react/no-string-refs)"
    

    You are getting this warning because have implemented the deprecated way of using refs (by using strings). Depending on your React version, you can do:

    React 16.3 and later

    constructor() {
      super();
      this.btnRef= React.createRef();
      this.state = { clicked: false };
      this.handleClick = this.handleClick.bind(this);
    }
    
    render() {
      return (
        
     
    ); }

    React 16.2 and older

    constructor() {
      super();
      this.btnRef;  //not necessary to declare the variable here, but I like to make it more visible.
      this.state = { clicked: false };
      this.handleClick = this.handleClick.bind(this);
    }
    
    render() {
      return (
        
    this.btnRef = el} className="glyphicon"> 
    ); }

    For even better readability, you could also do:

    render() {
      let myRef = (el) => this.btnRef = el;
      return (
        
     
    ); }

    Have a look at what the official documentation says on Refs and the DOM, and this section in particular:

    Legacy API: String Refs

    If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

提交回复
热议问题