Using JQuery plugins that transform the DOM in React Components?

前端 未结 4 636
梦毁少年i
梦毁少年i 2020-11-29 17:42

Some JQuery plugins don\'t just add behavior to DOM nodes, but change them. For example, Bootstrap Switch turns

4条回答
  •  臣服心动
    2020-11-29 18:15

    This is more of a philosophical question

    React was created to optimize DOM manipulations and has a lot of wiring behind the scenes to do so when a component's state changes via setState

    Doing so will cause said wiring to traverse its virtual DOM to find the nodes that need to be updated

    If you must use React, whether to try to keep a level of consistency in your coding, your best bet is to apply the JQuery DOM manipulation inside the componentDidMount like so...

    componentDidMount(){
        this.node = $("#"+this.props.id); // Keep a reference to the node
        this.chart = this.node.easyPieChart(); // Apply JQuery transformation and keep a reference
        this.percentTitle = this.chart.find(".percent"); // Keep a reference to the title
    }
    

    Having done so, on whatever your "refresh" method is, do NOT make any calls to setState, instead, call whatever update method your JQuery component may have, like so...

    componentWillMount(){
       this.interval = setInterval(this._doRefresh.bind(this), 1500);
    }
    
    _doRefresh( percentage ){
        // Note how setState is NOT being called here
        percentage = percentage || Math.floor (Math.random() * 100) // simulate since we're not getting it yet
        this.chart.data('easyPieChart').update(percentage); // call easyPieChart's update
        this.percentTitle.text(percentage);
    }
    

    At this point, if you're asking why use React at all, well, in my case, this component is an item in a list of other React components and was used to maintain consistency throughout the application... You may have a similar dilemma

    If, unlike me, you are unlucky enough that your component doesn't have an update method, and you can't make one, it might be time to rethink the approach altogether

提交回复
热议问题