In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to achieve jQuery-free in React, the article is very detailed, has a certain reference value, interested friends must read it!
Preface
First of all, we still want to say that jQuery is now the JavaScript tool library. According to the statistics of W3techs, he is currently used by 70.6% of the world's websites, while React is even less than 0.1%. However, a noteworthy trend for React is that its usage rate in the current * * traffic sites is *, with a proportion of 16%. This trend also shows the current technology trend across the front-end world, but the 70.6% figure also tells us that jQuery's king position in the JS library, even if React is used, may have to be used in conjunction with jQuery for a variety of reasons. But the size of React itself has made us uncomfortable with any heavy library, and in order to be compatible with IE8, we still need to use the 1.x version of jQuery, but design flaws at that time made it impossible for us to get it on demand like lodash. Because of the power of React and jsx, we don't need most of the functions of jQuery. From this point of view, his bloated size makes it more unbearable for developers, and jQuery-free is imperative.
First, select the DOM element
In jQuery, we are already familiar with using the sizzle selector to complete the selection of DOM elements. In React, we can use ref to get elements more specifically.
Import React from 'react'; class Demo extends React.Compoent {getDomNode () {return this.refs.root; / / get DomNode} render () {return (just a demo);}}
This is the easiest way to get node. What if there are multiple layers of structure nested? It makes no difference.
Import React from 'react'; class Demo extends React.Compoent {getRootNode () {return this.refs.root; / / get root node Dom Node} getLeafNode () {return this.refs.leaf; / / get leaf node Dom Node} render () {return (just a demo);}}
What if components and components are nested? It doesn't matter, the parent component can still get the root node of the child component.
Import React from 'react'; import ReactDOM from' react-dom'; class Sub extends React.Compoent {render () {return (a sub component);}} class Demo extends React.Compoent {getDomNode () {return this.refs.root; / / get DomNode} getSubNode () {return ReactDOM.findDOMNode (this.refs.sub) / / get the subcomponent root node} render () {return ();}}
The above uses the easy-to-understand API to explain the use of Ref, but it contains some methods that are not recommended by React and are about to be abandoned. If we use the method recommended by React, we can write it this way.
Import React from 'react'; import ReactDOM from' react-dom'; class Sub extends React.Compoent {getDomNode () {return this.rootNode;} render () {return (this.rootNode = c} > a sub component);} class Demo extends React.Compoent {getDomNode () {return this.rootNode / / get DomNode} getSubNode () {return this.sub.getDomNode (); / get the subcomponent root node} render () {return (this.rootNode = c} > this.sub = c} / >);}}
Some people may ask, how do the child components take the Dom Node of the parent component? from the point of view of the one-way data flow of the React, when we encounter this situation, we should notify the parent component through callback, and then let the parent component decide how to modify the Node. In fact, the parent component takes the Node of the child component rarely. In most cases, we pass the changes to the child component through props to get the Node of the child component. More often, it is to avoid a large number of re-rendering to modify some Node properties (such as scrollLeft).
II. DOM operation
JQuery provides a wealth of manipulation methods, but manipulating DOM elements one by one can be really annoying and error-prone. Through the idea of data-driven, React can easily add and delete view by changing the corresponding data of DOM.
Class Demo extends React.Compoent {constructor (props) {super (props); this.state = {list: [1,2,3],} This.addItemFromBottom = this.addItemFromBottom.bind (this); this.addItemFromTop = this.addItemFromTop.bind (this); this.deleteItem = this.deleteItem.bind (this);} addItemFromBottom () {this.setState ({list: this.state.list.concat ([4]),}) } addItemFromTop () {this.setState ({list: [0] .concat (this.state.list),});} deleteItem () {const newList = [... this.state.list]; newList.pop (); this.setState ({list: concat,}) } render () {return ({this.state.list.map ((item) = > {item})} tail insert Dom element header insert Dom element delete Dom element);}}
III. Monitoring of events
React implements a set of elegant event listening scheme by the way of root node agent, and it is very convenient to deal with the problems related to memory recovery in the component unmount.
Import React from 'react'; class Demo extends React.Component {constructor (props) {super (props); this.handleClick = this.handleClick.bind (this);} handleClick () {alert (' I'm a pop-up window');} render () {return (click on my pop-up box);}}
Here is a small detail is the timing of bind. Bind is to maintain the context of the corresponding function. Although you can also bind in onClick, bind in constructor is chosen because the former will bind every render and return a new function, which consumes performance.
However, after all, React event monitoring can only listen to root component, and we often have to listen to events on window/document. If resize, scroll, and some events that React can't handle well, such as scroll, we need to solve these problems ourselves. Event monitoring needs to do a lot of work to shield differences. Here we recommend a third-party library to complete this part of the work. The usage of add-dom-event-listener is slightly different from the native one, because this library is not designed to do polyfill, but the usage is still very simple.
Var addEventListener = require ('add-dom-event-listener'); var handler = addEventListener (document.body,' click', function (e) {console.log (e.target); / / works for ie console.log (e.nativeEvent); / / native dom event}); handler.remove (); / / detach event listener
Another option is bean, which achieves IE6+-level compatibility.
Fourth, the trigger of the event
Like event listening, there are excellent third-party libraries to handle both Dom events and custom events. For DOM events, bean is recommended, and if it is custom events, PubSubJS is recommended.
5. Document.ready
React as a view layer framework, the page usually has only one root node div for rendering React page components, so document.ready, you just need to put the script behind this div to execute. For the callback after rendering, we can use the componentDidMount lifecycle provided by React.
Import React from 'react'; class Demo extends React.Component {constructor (props) {super (props);} componentDidMount () {doSomethingAfterRender (); / / perform some operations, such as remote data acquisition and detection of DOM changes, after the component rendering is complete. } render () {return (just a demo);}}
VI. Attr method
JQuery uses the attr method to get the attributes of the Dom element. You can also read the attributes of the DOM element directly with Ref in React.
Import React from 'react'; class Demo extends React.Component {constructor (props) {super (props);} componentDidMount () {this.rootNode.scrollLeft = 10 / / after rendering, scroll the outer layer to 10px} render () {return (this.rootNode = c} style= {{width: '100pxshipping, overflow:' auto'}} > just a demo);}}
However, in most cases, we don't need to do it at all, because of React's one-way data flow and data-driven rendering, we can easily get and modify most of the DOM properties we need without going through DOM.
Import React from 'react'; class Demo extends React.Component {constructor (props) {super (props); this.state = {link:' / / www.taobao.com',}; this.getLink = this.getLink.bind (this); this.editLink = this.editLink.bind (this);} getLink () {alert (this.state.link) } editLink () {this.setState ({link:'/ / www.tmall.com',});} render () {return (jump link to get link modification link) }}
7. AddClass/removeClass/toggleClass
In the age of jQuery, we usually changed the appearance by getting the Dom element and then addClass/removeClass it. It has never been easier to modify styles in React through data-driven and third library classnames.
.fn-show {display: block;} .fn-hide {display: none;} import React from 'react'; import classnames from' classnames'; class Demo extends React.Component {constructor (props) {super (props); this.state = {show: true,}; this.changeShow = this.changeShow.bind (this) } changeShow () {this.setState ({show:! this.state.show,}) } render () {return (jump link to change reality);}}
VIII. Css
The css method of jQuery is used to set the style property of the DOM element. In React, we can directly set the style property of DOM. If you want to change it, just like the class above, use the data to drive it.
Import React from 'react'; class Demo extends React.Component {constructor () {super (props); this.state = {backgorund:' white',}; this.handleClick = this.handleClick.bind (this);} handleClick () {this.setState ({background: 'black',}) } render () {return (just a demo change Background Color);}}
IX. Data storage
Instead of being better at managing data than jQuery,React, we don't need to put the data in the attributes of Dom elements as we did in jQuery, but use state or internal variables (this.xxx) to save it, which we can compare and modify throughout the life cycle.
10. Ajax
Ajax is indeed a headache in dealing with compatibility issues, not to mention the compatibility of various forms of Xhr, and the function of jsonp, which does not belong to ajax, should also be considered at the same time. Fortunately, there is already a good third-party library to help us solve this problem. Here we recommend natty-fetch, a fetch library compatible with IE8, which is close to the fetch standard in API design, while retaining an interface similar to jQuery. Familiar with $. Ajax should be able to get started quickly.
Eleventh, Animation
React provides a plug-in for animation, ReactCSSTransitionGroup, and its low-level version ReactTransitionGroup. Note that the low-level version here is not a degraded version, but a more basic version that exposes more API.
This plug-in is inspired by Angular's ng-animate and is basically consistent in design. CSS3 animation is achieved by specifying the class name of the Transition, such as example, and adding the corresponding class name when the element enters and exits, respectively. For example, in this example, the entry adds example-enter and example-enter-active to the corresponding element, while the exit example-leave and example-leave-active class name. Of course, you can also specify different entry and exit class names. For admission, React also distinguishes between two types: one is ReactCSSTransitionGroup * rendering time (appear), and the other is that new elements are inserted (enter) after ReactCSSTransitionGroup has been rendered. These two types of entry can be configured separately using prop, and the timeout period can be prohibited or modified. Specific examples are detailed and explained in the links given above, so I won't repeat them in this article.
But at most, this plug-in only provides a solution for animation. What if I want to do something else in the process of animation? There's nothing he can do, and then it's ReactTransitionGroup's turn. ReactTransitionGroup provides six new life cycles for the animation elements he packages: componentWillAppear (callback), componentDidAppear (), componentWillEnter (callback), componentDidEnter (), componentWillLeave (callback), componentDidLeave (). These hook can help us accomplish some of the other things we need to do as the animation progresses.
However, there is one deficiency in the official plug-ins. Animation is only performed during entry and exit. What if my component is not mount/unmount, but just hidden and displayed? Here we recommend a third-party library: rc-animate, which basically continues the idea of ReactCSSTransitionGroup in terms of API design, but by introducing the attribute of showProp, he can handle components to show the entry and exit animation hidden in this case (as long as the attributes of the component on show/hide are passed to showProp). At the same time, this library also provides its own hook to achieve the callback when appear/enter/leave.
If you say that I am not satisfied with just incoming and outgoing animation, I want to achieve real-time animation similar to mouse dragging, what I need is a js animation library. Here I recommend a third-party library: react-motion, a big feature of react-motion is that unlike in the past, Bezier curves are used to define animation rhythm, introducing spring coefficients such as stiffness and damping to define animation, according to the author. Instead of entangling the length of animation and the Bessel representation which is difficult to master, it is most reasonable to adjust the stiffness and damping to debug the desired elastic effect. Readme provides a series of cool animation effects, such as this draggable list. Motion animates js by specifying defaultStyle and style, which are passed back to the changing style of the subcomponent.
{interpolatingStyle = >} the above is all the contents of the article "how to achieve jQuery-free in React". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.