Again talking about react.js realization of the original JS drag-and-drop effect caused by a series of problems _javascript skills

Source: Internet
Author: User


React originated in Facebook's internal project because the company was dissatisfied with all the JavaScript MVC frameworks on the market and decided to write a set of websites to build Instagram. After doing so, found that this set of things very easy to use, in May 2013 open source. Because react's design idea is extremely unique, belongs to the revolutionary innovation, the performance is outstanding, the code logic is very simple. So, more and more people start to pay attention to and use, think it may be the future of WEB development mainstream tools.



The last few days to write the drag, I left the question ... This time in the enthusiastic Bo friend prompted the correction of a number of small bugs, but also a drag of the edge detection part ... Let's talk about the drag.



First, do not directly manipulate the DOM elements



The concept of virtual DOM is used in react to avoid directly manipulating DOM elements, so we need to be aware of the DOM elements when we're working on them, and I used the Var dragbox= to get the parameters of the form. document.getElementById (' form ') goes to the DOM, but in fact records the initial position of from, which can be invoked when its subcomponents update the parent component's parameters. In the Myfrom component, the following code is obtained:


Onchildchanged:function (newstate) {/
* Below is the change place/
var computedstyle=document.defaultview.getcomputedstyle ( Reactdom.finddomnode (This.refs.dragBox), null);
Newstate.left=computedstyle.left;
Newstate.top=computedstyle.top;
/* Above for the amendment Department * *
This.setstate (newstate);
},


This allows you to manipulate yourself directly in the parent component, instead of calling it in a child component.



Ii. onmousemove and onmouseup events should be bound to the document



Drag and drop events, when the mouse is pressed in the Dragarea, you should detect the distance the mouse moves in the document and when it bounces. Otherwise directly bound in the form will have an indecent place, that is, drag the edge of the bar dragging near the time, if the mouse speed will be ineffective, the mouse back to drag the bar will automatically suck on the mouse. So using the Componentdidmount function of the react initialization phase, this function is loaded before it is invoked, which means that when the method is invoked, the component has been rendered onto the page, and the DOM can be modified at this time. This means that the corresponding event is then bound to the document above, the following code:


Componentdidmount:function () {
document.addeventlistener (' MouseMove ', (e) =>{this.move (e);},false);/* ES6 new feature, arrow function, need to rely on JSX compiler tool to run correctly
/document.addeventlistener (' MouseUp ', (e) =>{this.enddrag (e);},false);
} ,


So you can eliminate that little bug!



Third, increase edge detection



In general, we do not want to be able to drag out of the visual window, so this requires detection. Detects the position in four directions, that is, up, down, left, and right. Obviously, the distance between top and left side must be greater than or equal to 0, and the distance between the bottom and the right must be less than the viewport size minus the element width of the from itself.



Specific code:


move: function (event) {
var e = event? event: window.event;
var dBox = ReactDOM.findDOMNode (this.refs.dragBox);
if (this.state.flag) {
var nowX = e.clientX, nowY = e.clientY;
var disX = nowX-this.state.currentX, disY = nowY-this.state.currentY;
/ * Increase drag range detection * /
var currentLeft = parseInt (this.state.left) + disX;
var currentTop = parseInt (this.state.top) + disY;
var docX = document.documentElement.clientWidth || document.body.clientWidth;
var docY = document.documentElement.clientHeight || document.body.clientHeight;
if (currentLeft <= 250) {// Detect the left side of the screen, because my initial centering here uses a margin of 1/2 box width, so use 250px to determine the border
dBox.style.left = 250 + "px";
} else if (currentLeft> = (docX-dBox.offsetWidth + 250)) {// Detect right
dBox.style.left = (docX-this.state.offsetX) + "px";
} else {
dBox.style.left = currentLeft + "px";
}
if (currentTop <= 200) {// Detect the top of the screen, because my initial centering here uses a margin of minus 1/2 of the box height, so use 200px to determine the border <br> dBox.style.top = 200 + " px "; <br>} else if (currentTop> = (docY-dBox.offsetHeight + 200)) {// Detect <br> dBox.style.top = (docY-this.state.offsetY) +" px " ; <br>} else {<br> dBox.style.top = currentTop + "px"; <br>} <br>} 


PS: The new code has been updated on my GitHub, you can study it.



The background and principle of Reactjs



In web development, we always need to react to the changes in real time to the UI, and then we need to manipulate the DOM. Complex or frequent DOM operations are often the cause of performance bottlenecks (how high-performance, complex DOM operations are often an important indicator of the skills of a front-end developer). React introduced the virtual DOM mechanism: A set of DOM APIs was implemented with JavaScript at the browser end. When developing based on react, all DOM constructs are done through the virtual DOM, and whenever the data changes, react reconstructs the entire DOM tree, then react the current entire DOM tree against the previous DOM tree, resulting in a difference in the DOM structure. Then just make the actual browser Dom update for the part that needs to change. and react can batch process the virtual Dom refresh, the two data changes in an event loop are merged, for example, if you change the content of the node from A to B in succession, and then from B to A,react, the UI is not changed, and if it is manually controlled, This logic is often extremely complex. Although it is necessary to construct a complete virtual DOM tree each time, because the virtual DOM is memory data, performance is extremely high, and the actual DOM is only the diff part of the operation, thus achieving performance-enhancing purposes. In this way, while ensuring performance, developers will no longer need to pay attention to how a particular data change is updated to one or more specific DOM elements, but only to care about how the entire interface is render in any given data state.



If you write a Web page of server-side render as you did in the 90 's, then you should know that the server side is going to send HTML to the browser based on the data render. If this is the case because a user's click needs to change a state text, it is also done by refreshing the entire page. The server side does not need to know which small piece of HTML has changed, but only to refresh the entire page based on the data. In other words, any changes to the UI are done by refreshing the whole. and react this development model in high-performance way to the front end, every little bit of interface updates, you can think of refreshing the entire page. As for how to make local updates to ensure performance, it is the react framework to complete.



Use the example of chat application in the video of Facebook introducing react, when a new message comes along, the traditional development of ideas such as the above, your development process needs to know which data is coming, how to add new DOM nodes to the current DOM tree, and based on the react development ideas as shown below, You'll always need to be concerned about the overall data, how the UI changes between two of times, and then completely to the framework. As you can see, using react greatly reduces logical complexity, meaning that development is less difficult and there are fewer opportunities for bugs to be generated.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.