编程知识 cdmana.com

React (2) understanding JSX syntax format

Preface

React The framework recommends the use of DOM The grammar format is JSX grammar , Belong to a kind of JavaScript Expand ,React Use JSX To describe the user interface . We can think roughly of JSX yes JavaScript and HTML The combination of , But in the actual use process, there are some differences in details . This article will lead you to study systematically JSX The format of grammar .


One 、JSX The basic usage of grammar

1、 Use variables to define JSX Elements

const element=<div> Hello ,React!</div>; 

Here we need to pay attention to , The above code is not JavaScript character string , So there's no quotation marks around ; Neither HTML Code . It is JSX Grammar format .

React The minimum unit of application is “ Elements ”,JSX The grammatical format is React Recommended for declaring elements .

2、 Use variables to define nested JSX Elements

For nested JSX Elements ,JSX Grammar recommends using () Expansion .

const ulElement=(
  <ul>
    <li> The first name </li>
    <li> proxime accessit </li>
  </ul>
) 

Use () Expand nested JSX Elements , Make the format clearer . From the actual operation point of view , No writing () It's OK, too .

3、 stay JSX Using variables in the element

stay JSX You must use... To use a variable in an element {} Expansion , Variables can be used to JSX Element , It can also be used with JSX Elemental HTML Attribute value .

let name=' Zhang San ';
const strongElement=<strong> Hello ,{name}</strong>

let url='https://www.baidu.com';
const link=<a href={url}> use Baidu Search </a> 

4、 stay JSX Calling function in element

Those who have return The function that returns the value ,JSX Elements can be used like variables , utilize {} Expand calls to functions .

function getSum(a,b){
  return a+b;
}
let a=10,b=20;
const sum=<div>{a}+{b}={getSum(a,b)}</div> 

The case elements cited in the above cases (element、ulEelement、strongElement、link、sum) Can be directly used in ReactDOM.render() In the first parameter of the method , Act as a reference to the second parameter DOM The element placed in the node . With sum For example , The code is as follows .

ReactDOM.render(
    sum,
    document.querySelector('#app')
); 

Two 、JSX Grammatical rules of elements

JSX When writing elements, pay attention to the following grammatical rules :

  • JSX The element must have a unique root node .
  • JSX Marked in element class Attribute value must be used className attribute .
  • JSX Marked in element style Property values must be expanded with two braces , namely style={{}}.
  • JSX Comments inside tags in code must use {} Expansion , Comments outside the tag cannot be used {} Expansion .
  • JSX Tags in code must be paired or have an end tag .

Please read the following code carefully :

const element=(
  /* A complete JSX Elements : This comment is not inside any tags , So there's no need to {} Expansion */
  <div>       {/* Unique root node : This comment is inside the tag , Must use {} Expansion */}
    <div className="top">   {/*className Use of attributes */}
      {/*style The use of attributes must be double braces */}
      <div style={{width:'1200px',height:'40px',backgroundColor:'#3385ff'}}>
         Welcome to learn React frame .
        <img src=”images/01.jpg” />    {/* The tag must have an end tag */}
      </div>
    </div>
  </div>
);
ReactDOM.render(
  element,
  document.querySelector('#app')
); 

Run in the browser above , From the developer tools Elements In the tab, you can see the following structure as shown in the figure .

 Insert picture description here
You can see from the picture that ,id The property value is app Of div and class The property value is top Of div Between , There's an empty one div. This is due to satisfaction JSX The element must have a unique root node , And set the outermost layer div Tag pair . In order to prevent the outermost root node from being displayed in DOM In structure ,React It is recommended to use React.Fragment As all JSX The outermost root node of the element . The code should be in the following format .

const element=(
  /* A complete JSX Elements : This comment is not inside any tags , So there's no need to {} Expansion */
  <React.Fragment>       {/* Unique root node : This comment is inside the tag , Must use {} Expansion */}
    <div className="top">   {/*className Use of attributes */}
      {/*style The use of attributes must be double braces */}
      <div style={{width:'1200px',height:'40px',backgroundColor:'#3385ff'}}>
         Welcome to learn React frame .
        <img src=”images/01.jpg” />    {/* The tag must have an end tag */}
      </div>
    </div>
  </ React.Fragment >
); 

Now let's look at the developer tools Elements tab ,React.Fragment There is no mark pair in the mark position .
 Insert picture description here

3、 ... and 、 stay JSX Traversal array in format

stay JSX Traversing arrays in the format cannot use for loop , Only use ES5 The various methods provided for arrays . The following example shows an array of map() Method to traverse the array function .

example 1: Realize the navigation bar of the page JSX Format .
let navText=[' home page ',' Product display ',' Technology Outlook ',' Videoconferencing ',' Gold medal team ',' About us '];
let navLink=['index.html','product.html','technology.html','videol.html','team.html','about.html'];
const nav=(
  <React.Fragment>
    <div className="top">
      <div className="topContent">
        <ul>
          {
            navText.map((item,index)=>{
              return <li key={index}><a href={navLink[index]}>{item}</a></li>
            })
          }
        </ul>
      </div>
    </div>
  </React.Fragment>
); 

From the above code, you can see the following information about JavaScript Language in JSX Norms in grammar :

  • JavaScript Part in JSX Must be used in grammar {} Expansion .
  • The array is generated by traversing li When the tag , You must add key attribute , And set to the index value of the array .
example 2: There is one JSON Array , Each element has two attributes :isShow and file. among isShow The value is a logical value ,file The value is the string representing the image path . When isShow The value is true when ,file The specified picture will be displayed on the page ; When isShow The value is false when ,file The specified picture does not appear on the page .
let picture=[
  {isShow:true,file:'images/01.jpg'},
  {isShow:true,file:'images/02.jpg'},
  {isShow:false,file:'images/03.jpg'},
  {isShow:true,file:'images/04.jpg'},
  {isShow:true,file:'images/05.jpg'}
];
const img=(
  <React.Fragment>
    <h2> Picture appreciation </h2>
    <div className="picture">
      {
        picture.filter((item,index)=>{
          return item.isShow
        }).map((item,index)=>{
          return <img src={item.file} key={index} />
        })
      }
    </div>
  </React.Fragment>
); 

In the above code , array-based filter() Method pair picture Array , The screening criteria are isShow The value is true. Then use the filtered array elements map() Method , To display images on the page .

Four 、 stay JSX Format if sentence

stay JSX The format can not be used directly JavaScript Of if Of the statement , Here are five ways to explain what works .

example : Set a variable flag. Stipulated when flag=true when , The page shows a class named box Of div Mark ; When flag=false when , The page shows a class named fox Of div Mark .

1、 Use the ternary operator in JSX Implementation decision in

JavaScript The ternary operator provided (? :) Also known as “ Ternary operator ”. This operator is suitable for branch decision in two cases .

let flag=true;
const element=(
  <React.Fragment>
    {
      flag?
      <div className="box">
         I am a box Elements ......
      </div>
      :
      <div className="fox">
         I am a fox Elements 
      </div>
  }
  </React.Fragment>
); 

2、 Use the short circuit principle of logic and operator to realize the judgment

JavaScript And the logic operator provides (&&) Short circuit principle : When && The left side of the operation is false when , The right side is not counted . This operator is suitable for multi branch decision .

let flag=true;
const element=(
  <React.Fragment>
    {flag && <div className="box">
       I am a box Elements ......
    </div>}
    {!flag && <div className="fox">
       I am a fox Elements 
    </div>}
  </React.Fragment>
); 

In the above code , because flag The value of the variable is true, therefore !flag The values for false, be !flag && The elements on the right no longer count , And it won't be rendered .

3、 stay JSX The use of variables outside the format if Statement completion decision

since JSX The format is not allowed to be used directly if sentence , Then we won't be here JSX Format . We can do it in JSX Areas outside the format are used if sentence .

let flag=false;
let target;
if(flag){
  target=(
    <div className="box">
       I am a box Elements ......
    </div>
  )
}else{
  target=(
    <div className="fox">
       I am a fox Elements 
    </div>
  )
}
const element=(
  <React.Fragment>
    {target}
  </React.Fragment>
); 

In the above code, there is a definition called target The variable of , By means of JSX Out of format if Judgment of statement , Give Way target Variables get different values JSX Elements , In the end in React.Fragment Mark in use {target} The result of the judgment is quoted .

4、 stay JSX Using functions outside the format if Statement completion decision

We can also do that JSX Areas outside the format declare a function , Always use in function if Statement , And will eventually need to render JSX Format utilization return Statement returns .

let flag=true;
function getTarget(){
  if(flag){
    return (
      <div className="box">
         I am a box Elements ......
      </div>
    )
  }else{
    return (
      <div className="fox">
         I am a fox Elements 
      </div>
    )
  }
}
const element=(
  <React.Fragment>
    {getTarget()}
  </React.Fragment>
); 

In the above code, there is a definition called getTarget Function of , Internal use of this function if determine flag The value of the variable , And then use it return Statement will be required JSX Element returns . stay React.Fragment Tag alignment just needs to use {getTarget()} Call this function .


summary

This article is about React The second article in the series , Mainly for you to explain React In the frame JSX The writing form of grammar . Systematic learning JSX The writing form of grammar , For writing complex React The project helps a lot . Tomorrow will be a systematic explanation for you React How to use components .

About author

Front end of Xiaohai , have 18 year Web Project development and background training experience , In the front-end field, he has written systematic training materials , Yes Vue.js、 Wechat applet development 、uniApp、React I have deep attainments in the field of full stack development . To stay in Segmentfault, Hope to get to know more Web Colleagues in the field of development , take Web Develop and popularize vigorously . At the same time, we are willing to conduct in-depth technical research and business cooperation with you .

版权声明
本文为[Front end of Xiaohai]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224155041235e.html

Scroll to Top