Home > Article > Web Front-end > Thoughts caused by implementing native js drag and drop effect based on React.js_javascript skills
1. Causes & Ideas
I’ve always wanted to write a native js drag and drop effect, and I’ve been having fun learning react recently. So I used react to achieve this drag and drop effect.
First of all, the idea of drag effect is actually very simple. There are mainly three steps:
1. When onmousedown, start the draggable event and record the original coordinate parameters of the dragged element.
2. When onmousemove, record the distance moved by the mouse in real time, and calculate and set the new coordinate value based on the coordinate parameters of the first stage of the dragged element.
3. During onmouseup, close the draggable event and record the new coordinate value.
Note: The position of the element is mainly determined by the absolute positioning of top and left, so the css of the dragged element must be set to absolute positioning.
2. Auxiliary tools
Auxiliary tools mainly make the development process efficient and cool. In this demo, I would like to recommend a gulp+browser-sync development tool to everyone. Gulp has many functions. In this demo, the main function of gulp is to set up real-time compilation of jsx files in react. Of course, if you write css, It is sass, and you can also set up real-time compilation of sass. Using browser-sync, the main thing is to automatically refresh the page in real time. When we usually make pages and see the effect, we usually refresh the browser through F5, and then see the page. But with this plug-in, when you finish writing the code, just press ctrl+s to save, and the new effect will automatically refresh in the browser, and then you can see it.
Detailed explanation of usage:
Installation:
1. Install gulp in the node environment. I won’t go into details here. For the specific process, please refer to my blog post "Things You Must Know to Get Started with React.js"
2. To install gulp-livereload, on the command line or git bash, enter npm install --save-dev gulp-livereload
3. Install gulp-watch, on the command line or git bash, enter npm install --save-dev gulp-watch
4. To install browser-sync, on the command line or git bash, enter npm install --save-dev browser-sync
Configuration and explanation are as shown in the figure:
3. Define component construction page
Note: The code instructions here are all after the react-related modules are installed. For the installation process, please see my blog post "Things You Must Know to Get Started with react.js".
Rendering:
Component splitting ideas:
I thought it would be better to split the components into smaller parts, so I made input and button into one component respectively:
var React=require('react'); var MyInput=React.createClass({ render:function(){ return ( <div className="form-group"> <label htmlFor={this.props.labelId} className="col-sm-2 control-label{this.props.labelTip</label> <div className="col-sm-10"> <input name={this.props.name} type={this.props.type} onChange={this.props.onChange} className="form-control" id={this.props.labelId} placeholder={this.props.placeholder}/> </div> </div> ); } }); module.exports=MyInput;
var React=require('react'); var Button=React.createClass({ render:function(){ return ( <button type={this.props.type} className="loginButton">{this.props.ButtonTip}</button> ); } }) module.exports=Button;
Since there are many inputs that need to be specified, in this case, if you define it like me, you need to pass too many parameters, and in fact, most of the logged in inputs are fixed and there is no need to reuse them, so this is actually not a good idea. . It is better to write the input here directly.
The parent component after writing:
render:function(){ return ( <form className="form-horizontal" id="form" ref="dragBox" onSubmit={this.submitHandler} onMouseMove={this.move} onMouseUp={this.endDrag}> <DragArea callbackParent={this.onChildChanged} /> <div id="form-wrap"> <MyInput name="username" labelId={"userId"} labelTip={"用户名"} type={"text"} placeholder={"请输入用户名"} value={this.state.username} onChange={this.handleChange}/> <MyInput name="password" labelId={"pw"} labelTip={"密码"} type={"password"} placeholder={"请输入密码"} value={this.state.password} onChange={this.handleChange}/> <div className="form-group"> <div className="col-sm-offset-2 col-sm-10"> <div className="checkbox"> <label> <input name="checked" type="checkbox" checked={this.state.checked} onChange={this.handleChange} /> 记住我 </label> </div> </div> </div> <MyButton type={"submit"} ButtonTip={"登陆"}/> </div> </form> );
Note: Because the real dom node needs to be obtained in the demo, ref is defined.
Add css style and the page is complete! Finally, here comes the point! ! !
4. Communication between parent and child components to implement drag and drop
Note: Since the effect I want to achieve is that when the mouse is pressed on the sub-component DragArea, the entire form is dragged, so the DragArea starts the dragging and the form responds. Therefore, some state properties of the parent component must be passed to the child component at the beginning. Then when the mouse is pressed on the DragArea, the original coordinate parameters of the parent component must be found through the child component DragArea, and then the state properties in the parent component must be updated, and Tells the parent component that dragging is available. Parameters passed from the parent component to the child component are passed directly. The child component needs to pass events to pass parameters to the parent component. So define such a function in the parent component:
onChildChanged:function(newState){ //因为参数过多,所以把参数放到对象里面,通过对象来传 this.setState(newState); },
The sub-component needs to bind this function, such as the above code: callbackParent={this.onChildChanged}
In the child component, the response function is:
startDrag:function(e){ var dragBox=document.getElementById('form'); var newState={}; var event=e||window.event; event.preventDefault(); var computedStyle=document.defaultView.getComputedStyle(dragBox,null); newState.left=computedStyle.left; newState.top=computedStyle.top; newState.currentX=event.clientX; newState.currentY=event.clientY; newState.flag=true; <span style="color: #0000ff;"> this.props.callbackParent(newState);</span> }
In this way, the drag switch is activated in the sub-component, and the relevant parameters of from have been updated. The two other events of from, move and endDrag, are:
move:function(event){ var e = event ? event : window.event; //兼容IE的写法 if (this.state.flag) { var nowX = e.clientX, nowY = e.clientY; var disX = nowX - this.state.currentX, disY = nowY - this.state.currentY; ReactDOM.findDOMNode(this.refs.dragBox).style.left = parseInt(this.state.left) + disX + "px"; ReactDOM.findDOMNode(this.refs.dragBox).style.top = parseInt(this.state.top) + disY + "px"; } }, endDrag:function(){ var computedStyle=document.defaultView.getComputedStyle(ReactDOM.findDOMNode(this.refs.dragBox),null); this.setState({ left:computedStyle.left, top:computedStyle.top, flag:false }); }
At this point, drag and drop is implemented!
5. Reflection and Review
1. Theoretically, the drag effect can be realized in any element, and the idea of drag is the same, so theoretically, the functions of each drag process can be extracted and made into a Mixin, and then Can be called repeatedly. This was my initial idea, but I always made mistakes when passing parameters, responding, and binding elements. After searching for information, I couldn't find information on the simple writing methods of react and drag and drop. There were only some special plug-ins for react, and they were written in ES6. I can't understand them at my current level. So I gave up this way of writing for the time being. I hope that experts who have relevant ideas can share with me.
2. When the subcomponent in the article obtains the parameters from, it uses var dragBox=document.getElementById('form'); to find the dom, which seems to violate some concepts of react. But I'm not very familiar with how to get the dom of the parent component from the child component. I've tried defining refs=this.refs.dragBox in the parent component. Then it is passed to the sub-component, but I don’t know why the browser keeps reporting an error saying that this is not a dom node. Ask God for guidance.
3. The general way to write drag events is to define mousemove and mouseup events on the document, but these two events are associated with the parameters of from. In this case, if I define them in the document in react, I cannot track the related events. parameter. So I defined it on from. Is there a better way? Please share!
4. The revolution has not yet succeeded, comrades still need to work hard!
This demo has been uploaded to: https://github.com/LuckyWinty/dragDemo
The above is the entire content of this article, I hope it will be helpful to everyone’s study.