What's a bad practice with refs in React?

后端 未结 2 1730
孤独总比滥情好
孤独总比滥情好 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 02:16

    Hmm... Not sure it qualifies as an answer, but it became too long-form for a comment.

    Imagine you have a Dashboard that contains widgets showing various states of a system. Each widget has its own data source and its own controls. Perhaps they are even refreshed from time to time. However, when user wants to see an updated view of the system there is a "Refresh" button at Dashboard level. Implementing such a button is not trivial.

    If you are in a Redux application - you'd have a choice - "faking" dispatch('refresh') for all the children. To decouple it, each widget, upon loading registers an action, so that parent simply goes through all actions and fires them, when imperative refresh is needed.

    In a non Redux/Flux system, or in more complex/dynamic scenarios, this may not be possible or may not be as straightforward. It then may be better, complexity wise, to expose refresh method on all widgets and then access it from the parent (or, rather, owner):

    class WidgetA extends React.Component {
        refresh() {
            console.log('WidgetA refreshed');
        }
    
        render() {
          return (
            

    WidgetA

    ); } } class WidgetB extends React.Component { refresh() { console.log('WidgetB refreshed'); } render() { return (

    WidgetB

    ); } } class Dashboard extends React.Component { constructor() { super(); this.onRefresh = this.handleRefresh.bind(this); this.onRegister = this.handleRegister.bind(this); this.widgets = []; } handleRegister(widget) { this.widgets.push(widget); } handleRefresh() { this.widgets.forEach((widget) => { widget.refresh(); }); } render() { return (

    ); } }

    Something like that, with less verbosity, of course.

    As side note, I upvoted @skav answer and think that these scenarios should be avoided. This is an exception.

    CodePen Example

提交回复
热议问题