JSX grammar learning

Original link: https://www.iyouhun.com/post-222.html

Basic Concepts of JSX

JSX is short for JavaScript XML , which means writing XML-formatted code in JavaScript. It is the core content of React , it allows us to create elements in React easier, more intuitive, and improve development efficiency.

  • What is JSX?
    • JS extension syntax, XML syntax can be written in JS
  • Advantages of JSX?
    • UI interface can be declared more简洁、直观、高效

demo

We can test babeljs online on babel’s website, which can convert JSX code into JS code

image-20220607171437890

Note : JSX is a syntax extension of JavaScript , which cannot be used directly in the browser. The @babel /plugin-transform-react-jsx is built into the create-react-app scaffold to parse it and become the standard syntax of JavaScript .

Basic use of JSX

  • import react-dom
  • Create elements with JSX
  • Render with react-dom
 import ReactDom from 'react-dom'; const element = ( <div id="box"> <h1>JSX</h1> <ul> <li>tom</li> <li>jack</li> <li>tony</li> </ul> </div> ); ReactDom.render(element, document.getElementById('root'));

The above code runs successfully, and now React17x does not need to import the React package, because the dependencies for creating React elements are automatically imported when babel is converted. But if you use React16x then you also need to import React manually, how to verify? Just install the lower version of the React package.

Summarize

  • Import react-dom Create elements with JSX Render elements with react-dom
  • The 17x version of React does not need to be imported. If it encounters低版本in the future, it needs to be imported.

Replenish

  • vscode settings.json plus create tags using ement syntax hints in react
 "emmet.includeLanguages": { "javascript": "javascriptreact" }

Notes on JSX

usage details

  • Special attribute writing className htmlFor
  • Nodes with no content can use单标签
  • There must be a root node, you can use the <></> ghost tag, which is actually a shorthand for <React.Fragment></React.Fragment>
  • If JSX has newlines, it is better to wrap with ()

code example

  • special properties
 // class ---> className for ---> htmlFor 特殊属性<div className="box"> <label htmlFor="ck"></label> <input id="ck" type="checkbox" /> </div>
  • single label
 // <span className="icon-edit"></span> 没内容可以写成单标签形势<span className="icon-edit" />
  • has a root node
 // 1. 使用React.Fragment 代码片段import React from 'react'; import ReactDom from 'react-dom'; const element = ( <React.Fragment> <div>header</div> <div>footer</div> </React.Fragment> ); ReactDom.render(element, document.getElementById('root'));
 // 2. 使用<></>可以避免没必要的标签产生简写React.Fragment import ReactDom from 'react-dom'; const element = ( <> <div>header</div> <div>footer</div> </> ); ReactDom.render(element, document.getElementById('root'));
  • with parentheses
 // 有换行的时候最好使用()可以让标签对其,避免没必要的错误const element = ( <> <div>header</div> <div>footer</div> </> );

JSX embedded expressions

Use { } to embed JS expressions in JSX . Note that statements cannot be used.

  • Display data
  • perform operations
  • Ternary operation
  • use function
  • Using JSX
  • use annotations
 import React from 'react'; import ReactDom from 'react-dom'; // 数据const data = { name: 'tom', age: 18, }; // 函数const up = () => { return data.name.toUpperCase(); }; // jsx表达式const list = ( <ul> <li>jack</li> <li>tony</li> </ul> ); const element = ( <div> {/* 1. 使用数据注释推荐快键键(ctrl+/) */} <div>姓名:{data.name}</div> <div>年龄:{data.age}</div> {/* 2. 使用运算*/} <div>明年几岁:{data.age + 1}</div> {/* 3. 使用三元*/} <div>是否成年:{data.age > 16 ? '是' : '否'}</div> {/* 4. 使用函数*/} <div>姓名大写:{up()}</div> {/* 5. 使用JSX(jsx也是表达式) */} <div>朋友:{list}</div> </div> ); ReactDom.render(element, document.getElementById('root'));

JSX conditional rendering

  • Conditional rendering is done using branch statements if/else
  • Conditional rendering is done using the三元运算符
  • Conditional rendering using逻辑运算符

if/else conditional rendering

 const loading = true; // 不能在JSX中写语句,但,可以充分利用JS能力const getContent = () => { if (loading) { return <div>正在加载...</div>; } else { return <div>数据加载完毕,这是显示数据</div>; } }; const element = <div>{getContent()}</div>;

Ternary operator completes conditional rendering

 const loading = true; const element = ( <div> {loading ? <div>正在加载...</div> : <div>数据加载完毕,这是显示数据</div>} </div> );

Logical operation completes conditional rendering

 const loading = true; const element = ( <div> {loading && <div>正在加载...</div>} {loading || <div>数据加载完毕,这是显示数据</div>} </div> );

JSX list rendering

  • Can render JSX arrays
  • Render a list using map
  • Render a list using map directly in JSX
  • key attribute use

Can render JSX arrays

 // 1. const list = ['tom', 'jack', 'tony'] 把数组转换成如下JSX数组const list = [<li>tom</li>, <li>jack</li>, <li>tony</li>]; // 2. 把JSX嵌入在UL标签中const elemet = <ul>{list}</ul>;

Render a list using map

 // 1. 数据const list = ['tom', 'jack', 'tony']; // 2. 转jsx数组const list2 = list.map((item) => <li>{item}</li>); // 3. 使用const element = <ul>{list2}</ul>;

Rendering lists using map directly in JSX

 // 1. 数据const list = ['tom', 'jack', 'tony']; // 2. 使用map调用其实也是js表达式const element = ( <ul> {list.map((item) => ( <li>{item}</li> ))} </ul> );

key attribute usage

 // Warning: Each child in a list should have a unique "key" prop. // 1. 数据const list = ['tom', 'jack', 'tony']; // 2. 使用const element = ( <ul> {list.map((item) => ( <li key={item}>{item}</li> ))} </ul> );

JSX style – style way

  • style accepts a JavaScript object with camelCase named properties, not a CSS string
  • The key in style are named in small camel case to be consistent with JS accessing the properties of DOM nodes
  • React will automatically add the “px” suffix to the property whose inline style is a number, other units need to be added manually

demo code

  • Requirements: Remove the point of the previous list case ul , add the background style, set the font size, and set double the font size for the first p
 import ReactDom from 'react-dom' // 1. 数据const list = [ { id: 100, name: 'tom', age: 15 }, { id: 101, name: 'jack', age: 18 }, { id: 102, name: 'tony', age: 20 } ] +// 2. 样式+const styleObject = { + listStyle: 'none', + backgroundColor: 'pink', + fontSize: 20 +} // 3. 使用const element = ( + <ul style={styleObject} > {list.map(item => { return ( <li key={item.id}> + <p style=>姓名:{item.name}</p> <p>是否成年:{item.age > 16 ? '是' : '否'}</p> </li> ) })} </ul> ) ReactDom.render(element, document.getElementById('root'))

JSX style – className way

In most cases, the className attribute should be used to refer to a class defined in an external CSS style sheet

  • className sets the class name, which can only be a string like the class attribute requirements
  • If you need to set the class name according to the data, you can use { } to embed the JS expression to achieve

Demo code:

  • Requirement: Add the active class name on the element button according to the value of the isActive data

index.css code

 .button { width: 100px; height: 40px; border: 1px solid #eee; color: #999; border-radius: 4px; display: inline-block; text-align: center; line-height: 40px; box-shadow: 2px 2px 10px #ccc; cursor: pointer; user-select: none; } .button.active { background: #069; color: #fff; border-color: #069; } .button.block { display: block; width: 100%; }

index.js code

 import ReactDom from 'react-dom'; // 在src下新建index.css文件,导入进来即可import './index.css'; const isActive = false; const element = ( <span className={`button ${isActive ? 'active' : ''}`}>按钮</span> ); ReactDom.render(element, document.getElementById('root'));

JSX style – dynamic className

  • When you use className , you encounter multiple class name dynamic bindings, you can imitate the way vue uses objects
  • When binding the class name in vue , use {类名:布尔} to use the boolean value to decide whether to add the class name

For example: add the active class name according to the value of isActive data on the element button , add the block class name to the value of isBlock data

 import ReactDom from 'react-dom'; import './index.css'; // 数据const isActive = false; const isBlock = false; // 类名对象const classObject = { button: true, active: isActive, block: isBlock, }; // 转换成字符串const className = Object.keys(classObject) .filter((key) => classObject[key]) .join(' '); const element = <span className={className}>按钮</span>; ReactDom.render(element, document.getElementById('root'));

JSX style – classnames library

Use the native ability of JS to handle the dynamic binding of multiple class names. Of course, such a requirement has been solved by the classnames library.

install import classnames

 # 安装npm i classnames # 或者yarn add classnames
 // 导入import classNames from 'classnames'

Meet the classnames API

 // 1. 使用字符串classNames('foo', 'bar'); // foo bar // 2. 使用对象classNames({ foo: true, bar: true }); // foo bar // 3. 使用数组classNames(['foo', 'bar']); // foo bar // 4. 混合使用classNames('foo', { bar: true }); // foo bar

For example, it is still the above requirement: add the active class name according to the value of isActive data on the element button , and add the block class name to the value of isBlock data

 import ReactDom from 'react-dom'; // 1. 导入classnames import classNames from 'classnames'; import './index.css'; // 2. 数据const isActive = true; const isBlock = true; // 3. 产生类名const className = classNames('button', { active: isActive, block: isBlock, }); const element = <span className={className}>按钮</span>; ReactDom.render(element, document.getElementById('root'));

This article is reprinted from: https://www.iyouhun.com/post-222.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment