What's a bad practice with refs in React?

后端 未结 2 1762
孤独总比滥情好
孤独总比滥情好 2021-02-20 01:25

I\'m getting to learn React. Some guys of different sites tells everyone that using refs is a bad practice (yep, using them at all).

What\'s the real deal with it? Is it

2条回答
  •  名媛妹妹
    2021-02-20 01:59

    React requires you to think the react way and refs are kind of a backdoor to the DOM that you almost never need to use. To simplify drastically, the react way of thinking is that once state changes, you re-render all the components of your UI that depend on that state. React will take care of making sure only the right bits of the DOM are updated, making the whole thing efficient and hiding the DOM from you (kinda).

    For example, if your component hosts an HTMLInputElement, in React you'll wire up an event handler to track changes to the input element. Whenever the user types a character, the event handler will fire and in your handler you'll update your state with the new value of the input element. The change to the state triggers the hosting component to re-render itself, including the input element with the new value.

    Here's what I mean

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class Example extends React.Component {
    
        state = {
          inputValue: ""
        }
    
        handleChange = (e) => {
          this.setState({
            inputValue: e.target.value
          })
        }
    
        render() {
            const { inputValue } = this.state
            return ( 
              
    /**.. lots of awesome ui **/ /** an input element **/ /** ... some more awesome ui **/
    ) } } ReactDOM.render( , document.getElementById("app") );
    
    
    
    
    

    Notice how anytime the input value changes, the handler gets called, setState gets called and the componet will re-render itself in full.

    Its generally bad practice to think about refs because you might get tempted to just use refs and and do things say the JQuery way, which is not the intention of the React architecture/mindset.

    The best way to really understand it better is to build more React apps & components.

提交回复
热议问题