React Introductory Notes (i)-deep understanding of JSX

Source: Internet
Author: User
Tags cloudflare
"One", understanding JSX


  JSX is javascrpt XML--a class XML syntax that constructs tags inside a react component.
  JSX is not a new language, nor does it change JavaScript syntax, just a new feature based on ECMAScript, a syntax that defines a tree structure with attributes (DOM structure)
React can write components without using JSX, but using JSX can make code more readable, more semantic, abstract react elements, and so on. first, the use of JSX benefits



1, allows the use of familiar syntax to define the HTML element tree 2, provides a more semantic and easy to understand the label
3, the program structure is more easily visualized 4, abstract react element creation process
5, you can control the HTML tags at any time and generate these tags code 63, is native JavaScript



use JSX and code that does not use JSX as follows:


 
 



//Open and close tags, which are easier to read than function calls and object literals when building complex tree structures
//#Using JSX
<div className="red">Children Text</div>;
<MyCounter count={3 + 5} />;
// Set the "scores" attribute to a js object here
Var gameScores = {
   Player1: 2,
   Player2: 5
};
<DashboardUnit data-index="2">
   <h1>Scores</h1>
   <Scoreboard className="results" scores={gameScores} />
</DashboardUnit>;

//#Do not use JSX
React.createElement("div", { className: "red" }, "Children Text");
React.createElement(MyCounter, { count: 3 + 5 });

React.createElement(
   DashboardUnit,
   { "data-index": "2" },
   React.createElement("h1", null, "Scores"),
   React.createElement(Scoreboard, { className: "results", scores: gameScores })
);



Second, JSX syntax
[Note] The JSX code needs to be compiled into javscript by babel. Currently, the mainstream browser can recognize it normally, that is, it needs to be added in the head:


<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>


Two other files that React needs to rely on: react.js is the core library of React, and react-dom.js provides DOM-related functionality.
Write the JSX code in <script type='text/babel'> ... </script>


<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>


[Promotion] If the above core library is not found, you can download it on my github: https://github.com/mqy1023/react-basejs

JSX is a mixed-write syntax for HTML and JavaScript. When you encounter <JSX, it will be parsed by HTML. When you encounter {, it will be parsed by JavaScript.


var names = ['Alice', 'Emily', 'Kate'];
ReactDOM.render(
  <div>
  {
    names.map(function (name) {
      return <div>Hello, {name}!</div>
    })
  }
  </div>,
  document.getElementById('example')
);




Understand Array.prototype.map, return a new array


var friends = ['Jake Lingwall', 'Murphy Randall', 'Merrick Christensen'];
var listItems = friends.map(function(friend){
  return "<li> " + friend + "</li>";
});
console.log(listItems); // ["<li> Jake Lingwall</li>", "<li> Murphy Randall</li>", "<li> Merrick Christensen</li>"];



JSX allows JavaScript variables to be inserted directly into the template. If this variable is an array, all members of the array will be expanded


// The arr variable is an array, and the result JSX will add all its members to the template.
Var arr = [
   <h1>Hello world!</h1>,
   <h2>React is awesome</h2>,
];
ReactDOM.render(
   <div>{arr}</div>,
   document.getElementById('example')
);




In React, the HTML tags of a component are inextricably linked to the code that generates them. This means that we can easily take advantage of the powerful magic of Javascript
1, using the trinocular operator


// The arr variable is an array, and the result JSX will add all its members to the template.
Var arr = [
   <h1>Hello world!</h1>,
   <h2>React is awesome</h2>,
];
ReactDOM.render(
   <div>{arr}</div>,
   document.getElementById('example')
);



2, using variables / functions



getIsComplete: function() {
    Return this.state.isComplete ? 'is-complete' : '';
},
Render: function() {
    Var isComplete = this.getIsComplete();
    Return <div className={isComplete}>...</div>;

    //Or return function directly
    Return <div className={this.getIsComplete()}>...</div>;
}



3. Use logical & (&&) or logical or ( || ) operators
Since React does not output anything for a null or false value, a conditional decision can be implemented using a Boolean value followed by the expected string. If this boolean value is true, subsequent strings will be used


render: function() {
   return <div className={this.state.isComplete && 'is-complete'}>...</div>;
}



Logical OR, when this.props.name is empty, the className value is equal to is-complete



render: function() {
   return <div className={this.props.name || 'is-complete'}>...</div>;
}


4, the function call



var HelloWorld = React.createClass({
    render: function () {
        return <p>Hello, {(function (obj) { 
            return obj.props.name ? obj.props.name : "World";
        })(this)}</p>
    }
});


Third, create and render components


//1, React.createClass is used to create a component
Var HelloMessage = React.createClass({
   Render: function() {
     Return <h1>Hello {this.props.name}</h1>;
   }
});
//2, ReactDOM.render rendering component
ReactDOM.render(
   <HelloMessage name="John" />,
   document.getElementById('example')
);



"Two", JSX and HTML are different
First, render HTML tags and React components
The React.render method can render HTML structures as well as render React components.
1, rendering HTML tags, declare variables using the first letter lowercase


var myDivElement = <div className="foo" />;
ReactDOM.render(myDivElement, document.body);



2, rendering the React component, declaring the variable capitalized by the first letter


var MyComponent = React.createClass({/*...*/});
var myElement = <MyComponent someProperty={true} />;
ReactDOM.render(myElement, document.body);




Second, non-DOM attributes
1, the key (key)
Key is an optional unique identifier. When two components in the DOM are swapped, React can match the corresponding key and move accordingly. It does not need to completely re-render the DOM to provide rendering performance.




2, reference (ref)
Ref allows the parent component to maintain a reference to the child component outside of the render method. In JSX, you can define a reference by setting the desired reference name in the property.


render: function() {
   return <div> 
            <input ref="myInput" ...> </input>
          </div>
    );
}




Then you can get this reference anywhere in the component using this.refs.myInput. This object obtained by reference is called a support instance. It's not really a DOM, it's a description object that React uses to create a DOM when it's needed. You can access the real DOM node using this.refs.myInput.getDOMNode().

3, set the original HTML
For example, we have some content that is rich text input by the user, and we hope to display the corresponding style.


var content='<strong>content</strong>';
ReactDOM.render(
    <div>{content}</div>,
    document.body
);





The results page directly outputs the content:
React will perform HTML escaping by default, avoiding XSS attacks. If you don't want to escape, you can write:


ReactDOM.render(
    <div dangerouslySetInnerHTML={{__html: "<strong>content</strong>"}}></div>,
    document.body
);



Third, the event
In all browsers, the event name has been normalized and unified in the form of onXXX camel


var BannerAd = React.createClass({
    handleClick: function(event) {
        //...
    },
    render: function() {
       return <div onClick={this.handleClick}>Click Me!</div>;
    }
})




[Note] React automatically binds the scope of all methods of the component, so you don't need to manually bind



handleClick: function(event) {...},
Render: function() {
    //Anti-pattern ————Bind the component instance manually in React
    / / Function scope is not necessary
    Return <div onClick={this.handleClick.bind(this)}>...</div>;
}



Fourth, special attributes
Since JSX will be converted to native Javascript functions, there are some keywords we can't use - such as class and for, corresponding to JSX attributes written as className and htmlFor


//#Using JSX
ReactDOM.render(
     <label className="xxx" htmlFor="input">content</label>,
     document.getElementById('example')
);
//#Do not use JSX
ReactDOM.render(
     React.createElement('label', {className: 'xxx', htmlFor: 'input'}, 'content'),
     document.getElementById('example')
);




Five, style style
React normalizes all inline styles to a camel form, consistent with the sytle attribute of DOM in Javascript. The first significant parenthesis indicates that this is the JavaScript syntax, and the second significant parenthesis represents the style object.



React.render(
    <div style={{color:'red'}}>
        xxxxx
    </div>,
    document.body
);
////////////////////////////
var style = {
    color:'red',
    borderColor: '#999'
}
ReactDOM.render(<div style={style}>xxxxx</div>, document.body);



Six, notes
JSX is essentially Javascript, so you can add native javascript comments to your tags. Annotate two forms
a child node that is treated as an element is inlined in the properties of the element



Var content = (
   <Nav>
     {/* General comments, surrounded by {} */}
     <Person
       /* many
          Row
          Comment */
       Name={window.isLoggedIn ? window.name : ''} // End of line comment
     />
   </Nav>
);




"Three", JSX extended attributes
First, don't change props
If you know the properties of the component in advance, it is easy to write. For example, the component component has two dynamic properties foo and bar:


var component = <Component foo={x} bar={y} />;



In fact, some attributes may be added later, we can't determine from the beginning, we may write the following bad code:


var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad



This is wrong, because we manually added the property directly React can not check the attribute type error, that is, when we manually add the attribute type error, the console can not see the error message.

In the React setting, after props is initialized, props is immutable. Changing props can cause unimaginable consequences.
  Second, the extended attribute

To solve this problem, React introduces attribute extensions.



var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;



When we need to extend our properties, define a property object and introduce it by {...props}. React will help us copy it into the component's props property. The important thing is - this process is controlled by React, not a property that adds value manually.

When you need to cover it, you can write it like this:


var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'



"Four", JSX trap
First, custom HTML attributes
React does not display attributes that do not exist in the HTML specification into native HTML elements.


ReactDOM.render(
    <div dd='xxx'>content</div>,
    document.body
);




If you need to use a custom attribute, add the data- prefix.


ReactDOM.render(
    <div data-dd='xxx' aria-dd='xxx'>content</div>,
    document.body
);



Second, the component render render function returns attention points
If the return and JSX statements start on the same line, no parentheses are needed; otherwise, the parentheses are wrapped



/ / Correct writing 1
Var HelloMessage = React.createClass({
   Render: function() {
     Return <h1>
         Hello {this.props.name}</h1>;
   }
});
/ / Correct writing 2
Render: function() {
     Return <h1>Hello {this.props.name}</h1>;
}
/ / Correct writing 3
Render: function() {
     Return (
         <h1>Hello {this.props.name}</h1>);
}

//Error writing
Render: function() {
     Return
         <h1>Hello {this.props.name}</h1>;
}
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.