React -- three attributes of components (state, props, refs)

Keywords: Javascript Front-end React

Welcome to learn and communicate!!!
Updating continuously

Three properties of components (instances)

state attribute

State: state. Stateful components are complex components and stateless components are simple components

understand:
state is the most important attribute of the component object, and the value is the object (which can contain a combination of multiple key values)
The component is called "state machine", which updates the corresponding page display by updating the state of the component (re render the component, and render the component every time render is called)

be careful:

  • this in the render method of a component (a component is an object) is the component instance object

  • this is undefined in the method defined by the component. How to solve it?

    Force binding this: By function object bind()
    Arrow function (must be written as assignment statement)+Arrow function)
    
  • Status data cannot be modified or updated directly

Example: define a component that displays weather information

  1. The default display is hot or cool
  2. Click text to switch weather
    <script type="text/babel">
        // 1. Create component
        class Weather extends React.Component {
            constructor(props) {
                super(props)
                // Initialization status
                this.state = {isHot:false}
                // that = this
            }
            render () {
                // Read status:
                // Or directly const {isHot} = this.state, and then you can directly use {isHot? 'hot': 'cool'}
                // !!! Pay attention to the writing of this judgment
                return <h1 onClick={this.demo}>It's a fine day today{this.state.isHot ? 'scorching hot' : 'pleasantly cool'}</h1>
            }
            demo() {
                // Where is the demo----- On the prototype object of Weather for instance use
                // When a demo is called through a Weather instance, this in the demo is the Weather instance
                console.log(this.state.isHot);
                //Because the demo is used as a callback for onClick, it is not called through an instance, but directly
                //The method in the class turns on the local strict mode by default, so the this bit in the demo is undefined
                console.log(this)
            } 
        }
        // 2. Render component to page
        ReactDOM.render(<Weather />,document.getElementById('test'))

	//test
	const w = new Weather()
	w.demo()    //The second result is weather
    </script>

The effect is shown in the figure:

props attribute

understand:

  1. Each component object will have props (short for properties) attribute
  2. All properties of the component tag are saved in props

Function: transfer parameters

  1. Changing data is transferred from the outside to the inside of the component through tag attributes
  2. Note: do not modify props data inside the component

Basic usage of props:

<script type="text/babel">
// Create component
class Person extends React.Component {
    render() {
        console.log(this);
        // const {name,age,sex} = this.props;    // This method can omit this.props below
        return (
            <ul>
                <li>full name:{this.props.name}</li>
                <li>Gender:{this.props.sex}</li>
                <li>Age:{this.props.age}</li>
            </ul>
        )
    }
}
// Render component to page
ReactDOM.render(<Person name="Tom" age="18" sex="male"/>,document.getElementById('test'))
</script>

refs attribute

understand:
A tag within a component can define a ref attribute to identify itself

Syntax:

  1. ref in string form (no longer used)
<input ref="input1"/>
  1. ref in callback form
<input ref={(c)=>{this.input1 = c}}
//The function is a callback function, which is written here. React will help callback

Callback functions can be divided into inline callback functions and class bound callback functions. There are more cases of inline callback

<script type="text/babel">
        // Create component
        class Demo extends React.Component {
            state = {isHot:true}
            showInfo = ()=> {
                const {input} = this;
                alert(input1.value)
            }
            changeWeather = () => {
                // Get the original status
                const {isHot} = this.state;
                // Update status
                this.setState({isHot:!isHot})
            }
            render() {
                const {isHot} = this.state;
                return (
                    <div>
                        <h2>It's a fine day today{isHot ? 'scorching hot' : 'pleasantly cool'}</h2>
                        {/*Form of inline function:*/}
                        <input ref={(currentNode) => {this.input1 = currentNode;console.log('@',currentNode);}} type="text"/>
                        <br /><br />
                        <button onClick={this.showInfo}>Click the data on the left of my prompt</button>
                        <button onClick={this.changeWeather}>Click me to switch the weather</button>
                    </div>
                )
            }
        }
        // Rendering Components 
        ReactDOM.render(<Demo/>,document.getElementById('test'))
    </script>
  1. createRef create ref container (currently the most recommended form of react)
myRef = React.createRef() 
<input ref={this.myRef}/>

Disadvantages: if you want to create many ref containers, you have to create several with a few

    <script type="text/babel">
        // Create component
        class Demo extends React.Component {
            // After the call of React.createRef, a container can be returned, which can store the nodes represented by ref. the container is "dedicated to special personnel"
            myRef = React.createRef()
            // Display the data in the left input box
            showData = () => {
                const {input1} = this
                alert(this.myRef.current.value)
            }
            render() {
                return (
                    <div>
                        <input ref={this.myRef} type="text" placeholder="Click the button to prompt data"/>
                        <button onClick={this.showData}>Click the data on the left of my prompt</button>
                    </div>
                )
            }
        }
        // Rendering Components 
        ReactDOM.render(<Demo/>,document.getElementById('test'))
    </script>

Usage Summary: if conditions permit, avoid string type ref s as much as possible

Event handling in React

  • Specify the event handler through the onXxx attribute (note case)
  1. React uses custom (composite) events instead of native DOM events (i.e. repackaged in react) - for better compatibility
  2. Events in React are handled through event delegation (delegated to the outermost element of the component) - for efficiency
  • Get the DOM element object of the event through event.target -- don't overuse ref
  • Omit Ref: when the ref of the event is the ref of the operation, it can be omitted

Posted by Sealr0x on Mon, 11 Oct 2021 11:57:33 -0700