Create a project

When creating a project using scaffolding, you install the NPM package that initializes a React project

npm install create-react-app -g
Copy the code

Create a project

Create-react-app project nameCopy the code

Run the project

npm run start
Copy the code

JSX grammar

  • JSX can be seen as an extension of JS syntax, it is neither a string nor an HTML, it contains all the functions of JS, when the browser parse, encountered ‘ ‘<>’ will be as HTML code for compilation. When JSX creates the DOM, all nodes must have a unique root element wrapped around them

    function App () {
        return (  / / JSX syntax
        	<div></div>)}Copy the code

JSX writes JS internally

By wrapping JS code inside JSX with **{}, the browser will treat it as JS code and compile it when it encounters {}** while rendering.

  • Dynamic display of data and comments

    var name = 'react'
    function App () {
        return (
        	<div>{/* need to write this form */name}</div>)}Copy the code
  • You can use template strings

    var name = 'react'
    function App () {
        return (
        	<div>{' mainstream framework ${name} '}</div>)}Copy the code
  • Function methods can be called

    function seyHello() {
        return 'hello'
    }
    function App () {
        return (
        	<div>{ seyHello() }</div>)}Copy the code

PS: call method, not only can call the custom method, also can call the system built-in method, for use

  • JSX syntax does not support writing if judgmentsifStatement, if judged, requires writing a ternary expression

    var flag = false
    function App () {
        return (
        	<div>{ flag ? 'Hello' : 'I'm not ok'}</div>)}Copy the code
  • Add attributes to elements

    var name = 'item'
    function App () {
        return (
        	<div>
            	<span title="item"></span>
            	<span title={ name} ></span>
            </div>)}Copy the code

PS: When adding attributes to elements, there are generally two cases. One is to add the class name, and the other is to write the variable name inside curly braces by assigning the attribute value {}.

JSX event operation

  1. Event binding, ** events are added directly to the element using the camel name ={event handler function name}**

    function App () {
        return (
        	<div>
            	<button onClick={ handler }  >Click on the button</button>
            </div>)}const handler = () = > {
      // Event handler
    }
    Copy the code
  2. Event pass arguments

    • Method 1: Arrow function (recommended) [Event ={() => {event handler function name (parameter)}}]

      • return (
          <div>
          	<button onClick={() = >{handler(parameter)}}> Click event</button>
          </div>
        )
        
        const handler = (Receive parameters) = >{}Copy the code
    • Method 2: By using bind [event ={event handler function name. Bind (null, parameter)}, bind is the returned type, passing from the second parameter]

      • return (
        	<div>
              <button onClick={ handler.bind(null, parameter)} >Click on the button</button>
            </div>
        )
        
        const handler = (parameter) = >{}Copy the code
  3. Get event objects

    • Method 1: No parameters are passed by default, and the event handler’s default parameters are set to EV

      • return (
        	<div>
            	<button onClick={handler}></button>
            </div>
        )
        
        const handler = (ev) = > {
            console.log(ev)
        }
        Copy the code
    • Method 2: Arrow function parameters

      • return (
        	<div>
            	<button onClick={ (ev) = > { handler(ev) } }></button>
            </div>
        )
        
        const handler = ( ev ) = > {
            console.log(ev)
        } 
        Copy the code

Through the data

Map traverses the data. By traversing the data using a map, the map returns a new array. When traversing the data, as with VUE, you need to set the key attribute to the element.

const arr = [{
    name: 'Ming'.age: 18}, {name: 'Ming'.age: 18
}]
function App () {
    const newArr = arr.map((item,index) = > {
        return (
        	<li key={index}> {item} </li>)})return (
    	<ul>{newArr}</ul>)}Copy the code

Add the style

  1. When working with styles, you cannot use pseudo classes and media query Settings. You need to download the installation package to use them
npm install --save-dev radium
Copy the code
  1. When writing the class name, note that in JSX syntax, you need to change the class name toclassNameIn js, class is the keyword and cannot be used.

Inline style

const styles = {
    width: 100.height: 100.backgroundColor: 'red'
}
const styless = {
    font-size: 20.color: 'green'.backgroundColor: ` ` RGB (0, 1)
}
return (
	<div>/* Mode 1 */<button style={{ wdith: '100px'}} ></button>/* Mode 2 */<button style={ styles} ></button>/* Multiple inline styles can be written in the form of an array. You can use a teradata expression to determine which style to use */<button style={[
                styles.styless
         ]} ></button>
    </div>
)
Copy the code
  • When using inline style, because you can’t use pseudo classes and media queries, you need to download a specific package for processing, which component to use and where to introduce
import Radium from 'rudium'

const styles = {
  backgroundColor: 'green'.":hover": {
    backgroundColor: ` ` RGB (0, 1)}}return () {
    <button style={ styles } ></button>
}

export default Radium(App)
Copy the code

When exporting components, you need to pass theRadiumFunction to wrap the component, you can use pseudo-classes

  • If you need to use media queries, you need to wrap the components by introducing packages inside the displayed components
import { StyleRoot } from 'radium'
ReactDOM.render(
  <React.StrictMode>// The component needs to be wrapped with the change label so that the set media query can be used<StyleRoot> <App /></StyleRoot>
        
  </React.StrictMode>.document.getElementById('root'));Copy the code

Outreach style

  • Global outreach style

    • return (
          <div className={ 'box' }></div>
      )
      Copy the code

PS: Styles need to be introduced inside the common component inside index.js

import './app.css'
Copy the code
  • Single component externality style

When using a single component style, the stylesheet can be named in one of two ways. The first is a component.module.css with the same name as the component

// Style introduction differentiates global styles
import style from 'Style path'

return (
	<div className={ style.A class name} ></div>
)
Copy the code

PS: imported style file, you can call the internal style through the form of the object

Create components

import React, { Fragment } 'react'
Copy the code

In React, if you don’t want to create multiple DOM elements, you can use this tag to wrap the Fragment. Instead of importing the Fragment, you can use **<> instead

Creating a function component

In React, constructors are one of the most basic components.

If you want to put a component on a page, you can use the constructor name as the component’s name and import it into the page as an HTML tag.

import React from 'react'

function App () {
    return (
    	<div></div>)}export default App
Copy the code
  • Where to use itappComponents, where do you need to import components for use
  • The React package needs to be imported when creating components.
  • React parses all tags according to the first letter of the tag. If the first letter of the tag is lowercase, the tag is parsed according to the normal HTML tag. If the initial letter is uppercase, it is resolved as a component

Conclusion: The first letter of the component must be capitalized.

Component passing parameters (parent to child)

  1. The parent component
const obj = {
  name: 'This is passing the data back.'.data: 2021417.arr: [{name: 'yellow'.age: 18.id:0},
    {name: 'little blue'.age: 18.id:1},
    {name: 'little red'.age: 18.id:2}}]function App() {
  return (
    <div>
      <Header {. obj} ></Header>
      <About {. obj} ></About>// Single attribute pass<HeaderThe attribute name ={'Property value '}></Header>
    </div>)}Copy the code
  • It is recommended to use the deconstructed form to pass parameters. When requesting data, it cannot be single or several data, so use{... Data}Storage data is transferred uniformly
  1. Child components receive parameters
function About ({ arr }) {
  return (
    <div>
      {arr}
    </div>)}Copy the code
  • Data is deconstructed in the form of objects and used in the process. The name of the received parameter is custom, not fixed

Sets the default value and the specified data type without passing parameters

Packages need to be downloaded to handle default values or specify the type of data to be passed

npm i prop-types -D
// Import packages when used
import PropTypes from 'prop-types'
Copy the code
// Set no parameter to the default value
About.defauleProps = {
  name: 'hello'.age: 18
}

// What is the type of data to receive
About.propTypes = {
  // Specifies the type of parameter to be passed and must be passed
  arr: PropTypes.array.isRequired
} 

Copy the code
  • If the parameter must be passed. You need to add it after the typeisRequired

Creating a class component

// You need to import and deconstruct the Component, otherwise you are not setting up a component. The component needs to inherit methods

import React, { Component } from 'react'

class Heaber extends Component{
    // The render function must be set
    render() {
        return (
        	<div>Class components</div>)}}// Export the component
export default Header
Copy the code
  • When working with a component, you need to import it within the working component
import Header from './header.js'
Copy the code

Component passing parameters (parent to child)

  1. The parent component
const obj = {
  name: 'This is passing the data back.'.data: 2021417.arr: [{name: 'yellow'.age: 18.id:0},
    {name: 'little blue'.age: 18.id:1},
    {name: 'little red'.age: 18.id:2}}]function App() {
  return (
    <div>
      <Header {. obj} ></Header>
      <About {. obj} ></About>
    </div>)}Copy the code
  1. Child components receive parameters
  • In a class component, there is a fixed property, props, that can be used to receive external parameters.
import React,{Component} from 'react'

class Header extends Component{
  render() {
    // When printing, the value needs to be printed inside the function
    console.log(this.props.name);
    return (
      <div>{this.props.name}</div>)}}export default Header
Copy the code
  • Multiple data are received, which value is needed to deconstruct the value
render(
	const { name,data } = this.props
	return (
    	<p>{name}</p>
    	<p>{data}</p>))Copy the code

Display the default value if no parameter is passed

class Header extends Component{
  // Operate with static attributes
  static defaultProps = {
      name: 'Ming'
  }
  render() {
    // It needs to be deconstructed before it can be used normally
    const { name } = this.props
    return (
      <div>{name}</div>)}}Copy the code

JSX data is passed between components

  1. The parent component passes JSX data
function App() {
  return (
    <div>
      <Header>
      	<p>Pass JSX data; Class to accept</p>
      </Header>
      <About {. obj} >
        <p>Pass JSX data; The function to receive</p>
      </About>
    </div>)}Copy the code
  1. Subcomponent reception

    • classTo receive
    class Header extends Component{
      render() {
        return (
          <div>{this.props.children}</div>)}}Copy the code
    • Function internal reception
    function About (props) {
      console.log(props);
      return (
        <div>
          <p>{props.name}</p>
          {props.children}
        </div>)}Copy the code

The reception is the same. The childRE property under the same props will receive and render no matter how much JSX data is passed