Why React?

  • Componentized development concept, easy maintenance of the project
  • Just focus on the business logic and update the DOM quickly and efficiently
  • Massive surrounding ecological, friendly development environment

hello React

 <div id="root"></div>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script>
        const title = React.createElement('h1'.null.'hello React')
        ReactDOM.render(title, document.getElementById('root'));
    </script>
Copy the code

Use JSX syntax

JSX is a syntactic sugar that requires Bebel to compile. JSX syntax rules are as follows:

1. Do not use quotation marks when defining the virtual DOM

2. Use {} when adding js expressions to tags.

3. Use className for the style class

Style ={{}}

5. There is only one root label

6. The label must be closed

7. If the first letter of the tag is lowercase, it converts the HTML element with the same name. If uppercase, it is treated as a component

  <div id="root"></div>
    <! The virtual DOM is essentially an Object of type Object.
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
        const title = 'Hello JSX syntax';
        const vDOM =(<h1 style={{color: 'red' }}>{title}</h1>)      
        ReactDOM.render(vDOM,document.getElementById('root'));
    </script>
Copy the code

React uses JSX syntax when Vscode is automatically saved.

Download this plug-in

Uninstall this plug-in

JSX grammar exercises

    <div id="root"></div>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
        const data = ['vue'.'react'.'angular'];
         ReactDOM.render(
        <div>
            <h1 style={{color: 'red'}} >There are three main frameworks for the front end</h1>
            <ul>
                {data.map((item,index)=>{
                    return <li key={index}>{item}</li>
                })}
            </ul>
        </div>.document.getElementById('root'));
    </script>
Copy the code

Component based

React defines components in the following ways: function components and class components

<div id="root1"></div>
    <div id="root2"></div>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
        //1. Create functional components
        function MyComponent(){
            return <h1>Component Basics -- Functional components [for simple components -- stateless]</h1>
        };
        // Render to page
        ReactDOM.render(<MyComponent/>.document.getElementById('root1'));
  
        //2. Create the class component
        class MyComp extends React.Component {
            //render is a prototype object in MyComp for instance use
            render(){
                console.log(this)  // Component instance object
                return (
                    <h1>Component Basics -- Class Components [for complex components -- stateful]</h1>
                )
            }
        }
        ReactDOM.render(<MyComp/>.document.getElementById('root2'));
    </script>
Copy the code

What happens after reactdom.render (
, document.getelementByid (‘root2’)) is executed?

1.React parse component label and find MyComp component;

Find that the component is defined using a class, then create an instance of that class, and call the render method on the prototype with that instance;

3. Convert the virtual DOM returned by render into the real DOM and render it to the page.

Component instance property state

    <div id="root"></div>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
      // Note that methods in the class are partially in strict mode and do not point to instance-to-undefined unless called by a component instance
       class Weather extends React.Component{
           constructor(props){
               console.log('constructor')  // call once
               super(props)
               this.state = {isHot:false} 
            // this.changeweather = this.changeweather.bind (this) changes the direction of this in the class to generate a new function
               this.demo = this.changeWeather.bind(this)}render(){
               console.log('render')  // Call 1+n times n is the number of status updates
               // console.log(this) component instance object
               return (
                   <div>
                       <h1>State, one of the component cores</h1>
                       <h2 onClick={this.demo}>{this.state.ishot? 'Hot' : 'cool '}</h2>
                    </div>)}changeWeather(){
               // call n times
               const isHot = this.state.isHot
               // Change state with built-in API
               this.setState({
                   isHot:! isHot }) } } ReactDOM.render(<Weather/>.document.getElementById('root'));
Copy the code

The shorthand is as follows:

// same as above<script type="text/babel">
         class Weather extends React.Component {
             state = {isHot:true}   // This is also an instance property
             render(){
                 const {isHot} = this.state
                return (
                   <div>
                       <h1>State, one of the component cores</h1>
                       <h2 onClick={this.changeWeather}>Weather {isHot? 'Hot' : 'cool '}</h2>
                    </div>)}// Arrow function this points to the declaration context
             changeWeather = () = >{
                 const {isHot} = this.state
                 this.setState({isHot:! isHot}) } } ReactDOM.render(<Weather/>.document.getElementById('root'));
</script>
Copy the code

Component instance properties props

When the React element acts as a custom component, it converts the properties accepted by JSX into a single object to pass to the component. This object is called “props” (the object that the parent component passes to the child component)

<div id="root"></div>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.7.2/prop-types.min.js"></script>
    <script type="text/babel">
        class Person extends React.Component {
            render(){
                const {name,age} = this.props    // Note: props is read-only
                return (
                    <ul>
                        <li>name:{name}</li>
                        <li>age:{age}</li>
                    </ul>)}}// Type validation
        Person.propTypes = {
            name: PropTypes.string.isRequired,
            age:PropTypes.number,
        }
        / / the default value
        Person.defaultProps = {
            age:18
        }
         ReactDOM.render(<Person name='jiangyao'/>.document.getElementById('root'))
        // const batch = {name:'jiangyao',age:21}
        // ReactDOM.render(
       ,document.getElementById('root'));
    </script>
Copy the code

You can also write:

<script type="text/babel">
         class Person extends React.Component {
            // Whether the props are received in the constructor and whether the props are passed to super depends on whether you want to access the props through this in the constructor
            constructor(props){
                super(props)
                console.log('constructor'.this.props)
            }
            // Static attributes
            static propTypes = {
                 name: PropTypes.string.isRequired,
                 age: PropTypes.number,
            }

            static defaultProps = {
                 age:18
            }
            render(){
                const {name,age} = this.props
                return (
                    <ul>
                        <li>name:{name}</li>
                        <li>age:{age}</li>
                    </ul>
                )
            }
        }
         ReactDOM.render(<Person name='jiangyao'/>.document.getElementById('root'))
    </script>
Copy the code

A functional component cannot use the instance properties state and refs, but can use props, as follows:

<script type="text/babel">
       function Person(props){
           // Functional components can also use props
           const {name,age} = props
            return (
                <ul>
                    <li>name:{name}</li>
                    <li>age:{age}</li>
                 </ul>                                             
             )
        }
        Person.propTypes = {
            name: PropTypes.string.isRequired,
            age: PropTypes.number,
        }
        Person.defaultProps = {
            age:18
        }
        ReactDOM.render(<Person name='jiangyao'/>.document.getElementById('root'));
</script>
Copy the code

Component instance attribute refs

Define the three forms of ref:

1. Ref in string form may be abandoned in future versions, which is inefficient

2. Use ref in the form of a callback function (inline function), as shown below (second input example). Use ref in the form of a callback function (inline function), which is executed twice during the update process

3. Functions bind directly to classes (third input example)

 <script type="text/babel">
        class Demo extends React.Component{
            render(){
                return (
                    <div>
                        <input ref="input" type="text" placeholder="Click the button to display data"/>
                        <button onClick={this.showData}>Am I</button>
                        <input onBlur={this.showData2} ref={currentNode= >This.input2 =currentNode} placeholder=" placeholder "; /><input type="text" ref={this.showData3}/>
                    </div>
                )
            }
            showData = () = >{
                console.log(this)  // Component instances have refs
                console.log(this.refs.input)   // Get the real DOM
                const {input} = this.refs
                alert(input.value)
            }
            showData2 = () = >{
                const {input2} = this  // Notice the difference and hang input2 directly on the component instance
                alert(input2.value)
            }
            showData3 = (currentNode) = >{
                this.input3 = currentNode
                console.log(currentNode)
            }
        }
        ReactDOM.render(<Demo/>.document.getElementById('root'));
    </script>
Copy the code

The react. createRef call returns a container that stores the nodes identified by ref

<script type="text/babel">
         class Demo extends React.Component{
             myRef = React.createRef()
             showData = () = >{
                 console.log(this.myRef)   
                 alert(this.myRef.current.value)
             }
             render(){
                 return (
                    <div>
                        <input ref={this.myRef} type="text" placeholder="Click the button to display data"/>
                        <button onClick={this.showData}>Am I</button>
                    </div>
                 )
             }
         }
         ReactDOM.render(<Demo/>.document.getElementById('root'))
    </script>
Copy the code

React handles events

1. Specify the event handler using the onXxxx property

  • React uses custom (synthesized) events instead of native DOM events for better compatibility
  • React events are handled by event delegation (delegating to the outermost root element)

2. Use event.target to get the DOM element object where the event occurred

<script type="text/babel">
        // If the node on which the event occurred is the same as the node on which the operation was performed, use event instead of ref
        class Demo extends React.Component {
            render(){
                return (
                        <input onBlur={this.showVal} type="text"/>
                )
            }
            showVal = (event) = >{
                alert(event.target.value)
            }
        }
        ReactDOM.render(<Demo/>.document.getElementById('root'));
</script>
Copy the code

Uncontrolled component

<script type="text/babel">
        // Non-controlled components -- now use now
         class Login extends React.Component {
             render(){
                 return (
                    <form action="http://www.atguigu.com" onSubmit={this.handleSubmit}>User name:<input ref={current= >This. username=current} type="text" name="username"/><input ref={current= >this.password=current} type="password" name="password"/>
                        <button>The login</button>
                    </form>
                 )
             }
             handleSubmit = (event) = >{
                event.preventDefault()  // Prevent forms from being submitted by default
                const {username,password} = this
                alert('User name:${username.value}Password:${password.value}`)
             }
         }
         ReactDOM.render(<Login/>.document.getElementById('root'));
    </script>
Copy the code

The controlled components

Vue is similar to the two-way binding instruction V-model

    <script type="text/babel">
         class Login extends React.Component {
            // Initialization state
            state = {
                 username:' '.password:' '
            }
            render(){
                const {username,password} = this.state
                 return (
                    <form action="http://www.atguigu.com" onSubmit={this.handleSubmit}>User name:<input onChange={this.handleName} type="text" name="username" value={username}/>Password:<input onChange={this.handlePass} type="password" name="password" value={password}/>
                        <button>The login</button>
                    </form>
                 )
            }
            handleSubmit = (event) = >{
                event.preventDefault()  // Prevent forms from being submitted by default
                const {username,password} = this.state
                alert('User name:${username}Password:${password}`)
            }
            handleName = (event) = >{
                 this.setState({username:event.target.value})
            }
            handlePass = (event) = >{
                this.setState({password:event.target.value})
            }
         }
         ReactDOM.render(<Login/>.document.getElementById('root'));
    </script>
Copy the code

Introduce the life cycle

In applications with many components, it is important to free up resources when components are destroyed.

When the A component is first rendered into the DOM, A timer is set for it. This is called a “mount” in React.

Also, the timer should be cleared when the A component in the DOM is deleted. This is called “unmount” in React.

We can declare special methods for a class component that are executed when the component is mounted or unmounted. These methods are called “lifecycle methods.”

<script type="text/babel">
       // Create a component
        class Test extends React.Component {
            state = {
                opacity:0.5
            }
            // Uninstall the component
            death = () = >{
                ReactDOM.unmountComponentAtNode(document.getElementById('root'))}// Lifecycle -- called after the component has been mounted
            componentDidMount(){
                this.timer = setInterval(() = >{
                    let {opacity} = this.state
                    opacity -= 0.1
                    if(opacity <= 0) opacity = 1
                    this.setState({opacity})
                },200)}// Life cycle -- Components to be unloaded
            componentWillUnmount(){
                clearInterval(this.timer)
            }
            render(){
                // Write timer here to recursively change state infinitely and then call render again
                // setInterval(()=>{
                // let {opacity} = this.state
                / / opacity - = 0.1
                // if(opacity <= 0) opacity = 1
                // this.setState({opacity})
                // })
                return(
                    <div>
                        <h1 style={{opacity:this.state.opacity}}>React Lifecycle learning</h1>
                        <button onClick={this.death}>Click on the</button>
                    </div>
                )
            }
        }
        ReactDOM.render(<Test/>.document.getElementById('root'));
    </script>
Copy the code

The old version life cycle

Example:

    <div id="root"></div>
    <div id="test"></div>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
        // Create a component
        class LifeCycle extends React.Component{
            // When mounted -- constructor
            constructor(props){
                console.log('constructor')
                super(props)
                this.state = {count:0}
            }
            add = () = >{
                const {count} = this.state
                this.setState({count:count+1})
            }
            death = () = >{
                ReactDOM.unmountComponentAtNode(document.getElementById('root'))
            }
            force = () = >{
                // Force an update
                this.forceUpdate()
            }
            // When mounted -- the hook to which the component will be mounted
            componentWillMount(){
                console.log('componentWillMount')}// When mounted -- the component is mounted
            componentDidMount(){
                console.log('componentDidMount')}// A hook that controls component updates
            shouldComponentUpdate(){
                console.log('shouldComponentUpdate')
                return true
            }
            // The hook that the component will update
            componentWillUpdate(){
                console.log('componentWillUpdate')}// The component's updated hook
            componentDidUpdate(){
                console.log('componentDidUpdate')}// The hook that the component will unload
            componentWillUnmount(){
                console.log(' componentWillUnmount')}//render mounts hooks
            render(){
                console.log('render')
                const {count} = this.state
                return (
                    <div>
                        <h2>Current number: {count}</h2>
                        <button onClick={this.add}>I + 1 point</button>
                        <button onClick={this.death}>Click uninstall component</button>
                        <button onClick={this.force}>Force updates without changing data</button>
                    </div>)}}class Father extends React.Component{
            constructor(props){
                super(props)
                this.state = {name:'jack'}
            }
            test = () = >{
                const {name} = this.state
                this.setState({name:'sandwich'})}render(){
                const {name} = this.state
                return (
                    <div>
                        <div>Father</div>
                        <button onClick={this.test}>Click Change data</button>
                        <Son name={name}/>
                    </div>)}}class Son extends React.Component{
            // The component is going to receive the new props hook
            componentWillReceiveProps(props){
                console.log(props)
                console.log('componentWillReceiveProps')}render(){
                return (
                    <div>Son: {this. Props. The name}</div>
                )
            }
        }
        ReactDOM.render(<Father/>.document.getElementById('test'))
        ReactDOM.render(<LifeCycle/>.document.getElementById('root'));
    </script>
Copy the code

New edition life cycle

New hook: getDerivedStateFromProps() getSnapshotBeforeUpdate()

Going to abandoned hooks: componentWillMount () componentWillReceiveProps componentWillUpdate () ()

Reference: react.docschina.org/docs/react-…