First, JSX Introduction
① definition
Jsx=javascript XML is a class XML syntax that constructs tags inside a react component. React can work without the use of JSX, but using JSX can improve the readability of components, enhance JS semantics, clear structure, high level of abstraction, and code modularity. Therefore, it is recommended to use JSX in react.
② Features
1, element name first letter Capital
2, in line with nested rules
3, can write evaluation expression
4, hump-style naming
5, can not use JavaScript native function of some keywords, such as for and class. You need to replace htmlfor and classname.
How to use ③
1, the use of dynamic values: Jsx Two curly braces between the contents of {...} Rendering is a dynamic value, the curly braces indicate a JavaScript context, which can be either a variable or a function. For example:
var name= "Winty";
<p>{name}</p>
function Date (d) {return
[
d.getfullyear (),
d.getmonth () +1,
D.getdate ()
].join ('-);
};
<p>{date (new date ()}</p>
2. Note: First, the annotation in the child node should be wrapped in curly braces, and then a single-line comment/**/, or multiline comment//.
var hello=react.createclass ({
render:function () {return
<p name= ' winty ' >//set name
Hello, World
/* Multiline comment
multiline comment
//</p>}
});
3. Using CSS Inline styles
var style={
color: #000;
};
React.render (<div style={style}>....</div>,document.body);
4. Judge the conditions of use
Method 1, three-mesh operator
var hello=react.createclass ({
render:function () {return
<p>hello,{this.props.name? This.props.name: "Luckywinty"}</p>
}
});
Method 2,if-else Statement
var hello1=react.createclass ({
getname:function () {
if (this.props.name)
return This.props.name;
else return
"Luckywinty";
Render:function () {return
<p>Hello,{this.getName}</p>
}
});
Method 3, using logic | | Operator
var hello3=react.createclass ({
render:function () {return
<p>hello,{this.props.name| | " Luckywinty "}</p>
}
});
Introduction to ④ non-dom properties
There are 3 non-dom properties in JSX, respectively: dangerouslysetinnerhtml, ref, key.
dangerouslysetinnerhtml: Insert HTML code directly in JSX, but avoid using this property if you can avoid it.
Inappropriate use of InnerHTML can lead to cross-site scripting (XSS) attacks. Clean user input to display, often errors, improper purification is also caused by one of the reasons for Web page attacks.
After thoroughly understanding the consequences of security issues and properly purifying the data, generate objects that contain only the unique key __html, and the value of the object is the purged data. For example:
function Createmarkup () {return
{__html: ' First Second '};
<div dangerouslysetinnerhtml={createmarkup ()}/>
Ref: The parent component references a subassembly, and you can define a reference by setting the desired reference name in the attribute. For example:
...
Render:function () {return
<div>
<input ref= "myinput" .../>
</div>
}
...
///Then you can use This.refs.myInput to get the reference anywhere in the assembly.
Key: is an optional unique identifier that sets a unique key to the component and ensures that it is consistent throughout a rendering cycle, making it possible for react to more easily decide whether to reuse a component or destroy and build a component to improve rendering performance. For example:
var hello3=react.createclass ({
render:function () {return
<ul>
<li key= "1" >1</li>
<li key= "2" >2</li>
<li key= "3" >3</li>
</ul>
}
});
Second, the React component life cycle detailed
The component is essentially a state machine, the input is OK, the output must be determined. The state and result one by one correspond, making the program intuitive. A different hook function is triggered when the state transitions, giving the developer a chance to respond. You can use the idea of events to understand the state, but events and events are independent of each other, but different states may interact with each other.
All the states of a component are combined into the life cycle of the component. That is: Initialization stage-> operation stage-> destruction stage.
Functions that can be customized in different lifecycle
Initialization phase:
①getdefaultprops: Gets the default property, called only once, and is called after Createclass. Shared references between instances
②getinitialstate: Initializes the unique initialization state of each instance
③componentwillmount:mout is the meaning of loading, which means that the component is about to be loaded into the page and is the last chance to modify the state before render.
④render: The component generates the virtual node in the render function, and finally the virtual node is rendered to the page by react. Only This.props and this.state can be accessed, with only one top-level component, and it is best not to modify state and DOM output.
⑤componentdidmount: Components are loaded before they are invoked, which means that when this method is invoked, the component has been rendered onto the page, and the DOM can be modified at this time
The order in which these five functions are executed is from top to bottom. Note that Getdefaultprops is invoked only when the first instance of the component is initialized, that is, after the second instance is invoked from Getinitialstate. The default properties for all instances of the same component are the same.
Main test code:
<script type= "Text/babel" >
var hello=react.createclass ({
getdefaultprops:function () {
Console.log ("Getdefaultprops, 1");
},
getinitialstate:function () {
console.log ("Getinitialstate, 2");
return null;
},
componentwillmount:function () {
console.log ("Componentwillmount, 3");
},
Render:function () {
Console.log ("Render, 4");
Return <p>Hi,LuckyWinty!</p>
},
componentdidmount:function () {
console.log () Componentdidmount, 5 ");
}
;
React.render (
Run Result:
Run in phase:
①componentwillreceiveprops: This function is triggered when a component is about to receive a property, or when the attributes of the parent component change, and the property is given the opportunity to process the attribute before it is passed to the component. For example, modify, update the internal status and so on.
②shouldcomponentupdate: Triggered when a component receives a new attribute or a new state. This is a question function, which means we can tell react not to update a component. Because sometimes the attribute or state does not cause the component to update. If the component does not need to be updated, manually return the Shouldcomponentupdate to false so that react does not need to go through the render and diff algorithms to determine whether to update, thereby improving performance.
③componentwillupdate:render triggers before triggering, updates components, cannot modify properties and status
④render: Components in the render function to generate virtual nodes, and finally by react the virtual node into a real node rendering to the page, can only access this.props and This.state, only a top-level component, it is best not to modify the state and DOM output.
After the ⑤componentdidupdate:render, the real Dom is rendered and then called
Note: The order of execution of these five functions is also from top to bottom. This test code has been uploaded to: Https://github.com/LuckyWinty/ReactStudyDemo, Welcome to the Reference!
Destruction Phase:
①componentwillunmount: This function is called before the destroy operation is actually executed, giving the developer the last chance to do some cleanup work.
The meaning and usage of attribute and state
The meaning of the attribute:
Props=properties, attributes cannot be modified by the component itself, and the component's properties are passed in by the parent component.
Use of properties:
One), the key value pairs
(b), expand the definition (personally think is the definition of the object)
var props={one
: "123",
two: "All"
}
This definition, in theory, should be one={props.one} such calls, but this is more cumbersome to write, and if the data is modified, you need to modify the corresponding assignment, and can not dynamically set the property, so react added an expansion syntax:
Using the expand syntax, react automatically treats the variables and values in the object as an assignment to the property, so hello actually gets one, two two attributes, and if there are no three points, Hello is actually props object, You also need to remove variables and values from them when you use them
c), invoke the SetProps () function provided by react (hardly)
var instance=react.render (
The meaning of the state:
State, states are handled by things, constantly changing
Usage of State:
Getinitialstate: Initializing the state of an instance
SetState: Update component Status, once updated status, then will trigger the diff algorithm, check whether the content changes, if there are changes to update components, otherwise not.
Properties and Status comparisons
Similarities: All are pure JS objects, will trigger render updates, are deterministic.
attribute and state distinguish: the data that the component needs to modify at run time is the state
Iv. usage of events in react
event handler function: The React binding event handler is very similar to the HTML syntax, where all events are named in accordance with the native JavaScript specification and are triggered in the same context.
Writing functions
handleclick:function () {
...
}
Binding
Onclick={this.handleclick}
Detailed description of various events:
① Touch events on mobile devices: Ontouchcancel, Ontouchend, Ontouchmove, Ontouchstart
② Keyboard class Events: OnKeyDown, OnKeyPress, onKeyUp
③ Cut class Events: Oncopy, Oncut, Onpaste
④ Form class: onchange//content change is triggered, oninput//input box, onsubmit//prohibit form default jump behavior
⑤ events: onfocus, OnBlur
⑥ui element class: Onscroll
⑦ Mouse Scrolling Event: Onwheel
⑧ Mouse Type: OnClick, oncontextmenu//right-click menu, OnDoubleClick//Double-click, OnMouseDown, Onmouseenter, OnMouseLeave, OnMouseMove, onmouseout, OnMouseOver, onMouseUp
⑨ drag-and-drop events: OnDrop, Ondrag, Ondragend, OnDragEnter, Ondragexit, OnDragLeave, OnDragOver, ondragstart
Introduction to Event Objects
How to: You add an argument when you write an Event object handler function. Once you get this object, you can get some information from the object's properties.
For example:
Handlechange:function (event) {
console.log (event.target.value);
}
In the example, the event is the object of events, the Event.target is the property of the event object, the corresponding DOM element, and then the value of the element is retrieved.
Event Object Properties
Common Properties:
Other different types of events have different properties, and a simple understanding
Knowing some of the attributes of the event, we can easily get these attributes in the react, do some logic processing, realize some complex business functions, page effects, and so on.
For example, we can use the mouse event properties to display the mouse's coordinates in a region in real time:
<script type= "TEXT/JSX" >
var HelloWorld = React.createclass ({
getinitialstate:function () {
return {
x:0,
y:0
}
},
handlemousemove:function (event) {
this.setstate ({
x:event.clientx,
Y:event.clienty
});
render:function () {return
<div onmousemove={ This.handlemousemove} style={{
height: ' 500px ',
width: ' 500px ',
backgroundcolor: ' Gray '
}}>
{this.state.x + ', ' + this.state.y}
</div>;} '
);
React.render (<HELLOWORLD></HELLOWORLD>, document.body);
</script>
x component definition of Synergy: Component Synergy is essentially an organization and management approach to components.
The purpose of collaborative use of components: logic clarity, Code modularity, encapsulation details, code reusable.
How the components work together:
① components are nested using: that is, a parent component is wrapped in a component, which is essentially a parent-child relationship. The following figure describes:
Instance code:
var react = require (' react ');
var commentlist=require ('./commentlist.jsx ');
var commentform=require ('./commentfrom.jsx ');
var Commentbox = React.createclass ({
render:function () {return
(
<div classname= "Commentbox" >
Communication between parent and child components:
Parent component->: through attributes, the parent component passes data through attributes to the subassembly
subassembly-> Parent component: In essence, subcomponents cannot communicate to parent components. But you can communicate indirectly by triggering an event, which is a delegate.
Nested combination Disadvantage:
The specific implementation of a parent-child relationship needs to be considered, and written hastily will lead to confusion and difficult code maintenance.
Unable to master all the details, the user only knows the component usage, does not know the implementation detail, encounters the problem difficult to fix
②mixin: that is, you can abstract the same code, encapsulate it into a function, and then call it.
Purpose of mixin: transverse extraction of the similar code of the component
Similarity concept: Face to face programming, plug-in
Instance code:
var time=react.createclass ({
mixins:[intervalmixin (1000)),
getinitialstate:function () {return
{ secondelapsed:0};}
,
ontick:function () {
this.setstate ({secondelapsed:this.state.secondelapsed+1});
} ,
render:function () {return
(
<div>seconds elapsed:{this.state.secondselapsed}</div>
);
}
});
Mixin are fairly simple, they are objects that are mixed into a component class. React is implemented more deeply in this regard, which prevents the silent function from overwriting and also supports multiple mixin blending. However, these features can cause conflicts in other systems. For example:
React.createclass ({
mixins:[{
getinitialstate:function () {return {a:1}}}
],
getinitialstate: function () {return {b:2}}}
);
In this way, the Getinitialstate method is defined in both the Mixin and the component classes, and the resulting initial state is {a:1,b:2}. If duplicate keys exist in the objects returned by methods in the mixin and in the component class, react throws an error to alert the problem.
Bi-directional binding in react
The idea of the creation of the
react is different from those of angular, react is one-way data binding. So how do you implement a two-way binding effect like angular? See Code:
<! Bidirectional data binding ZH-CN in DOCTYPE html>
Effect Picture (no CSS style, a bit not elegant, forgive):
The above is the entire content of this article, I hope to help you learn.