Deprecation warning using this.refs

后端 未结 3 1600
忘了有多久
忘了有多久 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条回答
  •  -上瘾入骨i
    2020-11-27 07:14

    The reason this ESLint rule exists is that string Refs are on their way out. However, for the code above I would recommend to not use a Ref in the first place.

    Don't Overuse Refs

    React's advantage is that it is declarative. Meaning, we have state and an expression (returned JSX) of how the UI (more precisely the DOM) should look given a certain state.

    Whatever can be done using just state and UI expression, should be done this way. The problem with the use of a Ref in the code above is that it makes the code imperative. We can't understand how the DOM will look just from the JSX. Here is how you could achieve the same result in a declarative way:

    export class myComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = { 
                active: false 
            };
        }
    
        handleClick = () => {  // with arrow function there is no need for binding. 
            this.setState(
                prevState => {
                    return {
                        active: !prevState.active
                    }
                }
            )
        }
    
        render() {
            return (
                
    Hello World
    ); } }

    Refs should be used when state and UI expression aren't enough, and you need access to the actual DOM. For example, focusing on an input field, scrolling to an element, or getting the exact width and height of an element.

    If you do use Refs, avoid string refs

    String refs harm performance, aren't composable, and are on there way out.

    string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. [Official React documentation]

    [resource1][1], [resource2][1]

    Option #1: Use React.createRef

    class MyComponent extends Component {
    
        constructor(props) {
            super(props)
            this.myRef = React.createRef() // create a ref object 
        }
    
        render() {
            return 
    // Attach the ref property to a dom element } }

    Option #2: Use a ref callback

    class MyComponent extends Component {
    
        constructor(props){    // Optional, declare a class field
            super(props)
            this.myRef=null    
        }
    
        render() {
            return 
    this.myRef=ref }>
    } // Attach the dom element to a class field }

提交回复
热议问题