问题描述:

I'm new to react, I get enough to know that manipulating the dom composed by react with Jquery is a very bad Idea. However is it a bad Idea to manipulate styles on dom components rendered by react with Jquery?

ReactDom.render( <LoginPage/>, document.getElementById('root') );

//after render call activateJQ();

var activateJQ = function(){

$('button').animate({

backgroundColor: "#aa0000",

color: "#fff",

width: 500

}, 1000 );

$('.error-msg').css("color","red");

};

It works on this page, but I would like to incorporate this into more complex pages that change states and rerender. How will react address components with added stylings?

网友答案:

The short answer: Yes, you can. But it is a very bad idea, and you will regret it if you do.

In your specific example using jQuery to apply styling (color or error messages) and animated styling (background-color etc to buttons) does not break anything.

That said, there are specific advantages to using react to apply styling: You are forced to apply styling (in css classes you assign to your components) and animation (in componentDidMount() or using <ReactCSSTransitionGroup>) at the right moment in the life cycle of a component. This makes your code easier to debug: if your styling breaks, you can find all suspect code in the right place inside react.

Remember: react is a dynamic engine, that can change the structure of your DOM based on user actions. And your css styling is closely coupled to your DOM structure, so you would want to have them in sync (and thus managed in the same place in your code).

In your specific case, I can think of at least one scenario where your react + jQuery setup breaks down:

  • ReactDOM.render() runs, and starts react engine
  • initial react render cycle has 2 e.g. buttons and 1 error message
  • jQuery is applied, animating the 2 buttons and 1 error message
  • user does some clicking
  • react re-renders with 2 new buttons and 1 new error message
  • Your jQuery does NOT run again
  • the new react buttons and error message do not get the new styling

Or, if you call activateJQ() after each render() in react:

  • the 1000ms timeout is likely to run out of sync with your render cycles, so may result in unnecessary DOM updates or worse, break if react changes DOM during jQuery update
  • the jQuery class-selector with styling updates is a notoriously crude (and therefore performance-killing) instrument. It needs to traverse entire DOM every single time to do updates, which includes updates to components that do not even need an update. Managing styling in react is much more efficient: styling is only applied to components that need it, and only at the time they need it.

As your application grows, you will find that mixing react and jQuery to manage DOM and styling (which are heavily interdependent) will become unmanageable.

相关阅读:
Top