React learning --- JSX learning

React Learning — JSX

1 Overview

​ JSX is the core component of React. It uses XML tags to directly declare the interface, and interface components can be nested with each other. It can be understood as writing a language similar to XML in JS, a grammar that defines a tree structure with attributes (DOM structure), its purpose is not to be implemented in browsers or engines, its purpose is to pass various compilers These tags compile to standard JS language.

​ Although you can not use JSX syntax at all and only use JS syntax, it is still recommended to use JSX, which can define a tree structure syntax containing attributes, similar to HTML tags, and easier to read code.

​ This is JSX, which is an extended syntax of JavaScript. We recommend using this syntax in React to describe UI information. JSX might remind you of a templating language, but it has the full power of JavaScript.

​ We call this kind of thing, react element, which can describe UI information very well (combination of dom nodes)

The difference between XML and HTML:

  1. The syntax of the HTML tag language is loose, while the syntax of XML is strict and case-sensitive
  2. HTML is mainly for page transmission, XML is mainly for data transmission
  3. All tags in HTML are defined, and all tags in XML are custom

2. JSX reconstruction Hello world

ReactDOM.render(
 <h1>欢迎进入 React 的世界</h1>,
 document.getElementById('root') // 渲染到哪里
)

Parameter 1 is quite strange here, it is not a string, it looks like pure HTML code written in JavaScript code. Is the syntax wrong? This is not legal JavaScript code, the "tags written in JavaScript" syntax is called JSX - JavaScript XML.

3. js expression in JSX syntax

  1. embedded js expression

    js expressions must be embedded in jsx syntax by means of {expression}.

    <h1>欢迎进入 React 的世界 {
          
           1+1 } </h1>
    
  2. attribute binding

    <h1 title={
          
           a + 1 }>欢迎进入 React 的世界</h1>
    

    class binding with className

    <h1 className={
          
          `big ${
            
            i==index?'active':''}`}>欢迎进入 React 的世界</h1>
    

    Dynamic binding of style

    <h1 style={
          
          {
          
          width:20,fontSize:20}} >user</h1>
    
    

    When using for in label, it should be changed to htmlfor

    <h1 htmlFor="xxx">欢迎进入 React 的世界</h1>
    
  3. Array rendering

    direct rendering

    const list = [
     <li key="1">sunyang</li>,
     <li key="2">lining</li>,
     <li key="3">chenhe</li>
    ]
    

    Array members can be simple data number, string, or dom elements

    process and render

    When the array member is composite data, it needs to be processed by the forEach or map method before rendering the output; the function of map is to render the data into labels

    const list = [
     {
          
           name:'sunyang',age:10 },
     {
          
           name:'lining',age:20 },
     {
          
           name:'chenhe',age:30 }
    ];
    <ul>
     {
          
          
     list.map(function (item) {
          
          
     return <li key={
          
          item.age}>{
          
          item.name}</li>
     })
     }
    </ul>
    
  4. Comments in JSX syntax

    Writing method 1 (not recommended): { // Comments // … }

    Writing method 2 (recommended, write multiple lines into a single line): { /* single-line comment */ }

    Writing method three (multiple lines): { /* * multi-line comment */ }

Comments will be ignored during babel transformation and will not appear in the final js code.

  1. Basic syntax rules of JSX

    1. There must be one and only one root node
    2. Multi-tags are written in parentheses to prevent JavaScript automatic semicolons from being executed later.
    3. Use HTML rules to parse HTML tags starting with <
    4. When encountering a code block starting with {, use JavaScript rules to parse it
    5. A single tag cannot omit the end tag, must end />
    6. JSX allows inserting JavaScript variables directly in templates
    7. If the variable is an array, all members of the array will be expanded and added to the template

4. Case

insert image description here

Create a components file in the project src folder to deliver the component

Create an Input.jsx file under the components folder


//rcc 生成class形式的组件
//rsf 生成函数式的组件
import './Input.scss'
import React, {
    
     Component } from 'react';

class Input extends Component {
    
    
    render() {
    
    
        // 像class这样编译为js后会产生歧义的代码, 必须按照react规定的语法书写, 并且必须遵循小驼峰命名法
        return (
            <div className='input'>
                <input type="text" placeholder='输入商品名称' />
                <span>搜索</span>
            </div>
        );
    }
}

export default Input;

Create the Input.scss file under the components folder

.input{
    
    
    display: flex;
    margin: 10px;
    input{
    
    
        height: 40px;
        outline: none;
        padding-left: 20px;
        border: 1px solid #ccc;
        flex:1;
    }
    span{
    
    
        width: 80px;
        display: inline-block;
        text-align: center;
        height: 40px;
        line-height: 40px;
    }
}

Create a List.jsx file under the components folder

import React, {
    
     Component } from 'react';
//本地图片必须import导入, 才能使用
import logo from '../logo.svg'

import './List.scss'

class List extends Component {
    
    
    constructor(props){
    
    
        super(props);
        this.state = {
    
     //定义组件状态
            arr:[
                {
    
    name:'护肤',pic:logo},
                {
    
    name:'彩妆',pic:logo},
                {
    
    name:'香氛',pic:logo},
                {
    
    name:'进口酒',pic:logo},
                {
    
    name:'国产酒',pic:logo},
                {
    
    name:'精品奢货',pic:logo},
                {
    
    name:'食品百货',pic:logo},
                {
    
    name:'母婴专区',pic:logo},
                {
    
    name:'直播专区',pic:logo},
                {
    
    name:'特卖专场',pic:logo},
            ]
        }
    }
    render() {
    
    
        return (
            <div className='list'>
                {
    
    
                    // 列表渲染, 使用js中的map函数
                    this.state.arr.map((item)=>{
    
    
                        return (
                            <div className="cate">
                                <img src={
    
    item.pic} alt="" />
                                <div className="name"> {
    
    item.name} </div>
                            </div>
                        )
                    })
                }
            </div>
        );
    }
}

export default List;

Create a List.scss file under the components folder

.list{
    
    
    display: flex;
    flex-wrap: wrap;
    .cate{
    
    
        width: 20%;
        text-align: center;
        img{
    
    
            width: 80%;
            border-radius: 50%;
        }
    }
}

App2.jsx file in src folder

import logo from './logo.svg';
import './App.css';
import React from 'react';
import Input from './components/Input'
import List from './components/List'

class App extends React.Component{
    
    
  constructor(props){
    
     //在constructor中对组件状态进行初始化
    super(props);
    this.state = {
    
     //初始化组件状态
        
    }
  }

  render(){
    
     //render是必须的, render中必须通过return返回 组件模板
    return (
      <div className="App">
          {
    
    /* 渲染Input组件 */}
          <Input />

          {
    
    /* 渲染List组件 */}
          <List />

      </div>
    )
  }
}
export default App;

In the index.js file

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App2';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

tMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Guess you like

Origin blog.csdn.net/m0_53181852/article/details/127789256