html and js projects introduce parent-child or child-child value transfer into react framework

Keywords: node.js html5 React

1, Introduction of react

Three files need to be imported

1.react.js

https://unpkg.com/react@17/umd/react.development.js

https://unpkg.com/react-dom@17/umd/react-dom.development.js

2.babel.js (because react is written in xml, it needs to be compiled with babel to avoid error)

https://unpkg.com/@babel/standalone/babel.min.js

You can directly import or open the connection to download js code. I download the code locally for demonstration

<script src="./static/react.development.js"></script>
<script src="./static/react-dom.development.js"></script>
<script src="./static/babel.js"></script>

Be sure to follow the above order, otherwise an error will be reported

2, refs tag element to get DOM instance

1. Create method getValue: use the arrow function to omit the creation of bind

2. Execute in the method to obtain the value required by the refs tag element

3.ref is marked on the element and named after the equal sign

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .styleClass {
        background-color: red;
        color: blue;
    }
</style>

<body>
    <div id="app"></div>
</body>
<script src="./static/react.development.js"></script>
<script src="./static/react-dom.development.js"></script>
<script src="./static/babel.js"></script>
<script type="text/babel">
    // Parent component creation
    class Home extends React.Component {
        render() {
            return (
                // div must be added to the outermost layer of component nesting
                <div>
                    <Header title={this.props.header} ></Header>
                </div>
            )
        }
    }

    // Subcomponent creation
    class Header extends React.Component {
        constructor(props) {
            super(props);
        }
        //Create a method, click the button and execute alert
        getValue = () => {
            //Get the element marked by ref and get the value in the input box
            alert(this.refs.msg.value);
        }
        render() {
            // ref is named msg and placed in the input element
            return (
                <div>
                    <input ref='msg' />
                    <h1 className="styleClass">{this.props.title}</h1>
                    <button onClick={this.getValue}>Click to get content</button>
                </div>
            )
        }
    }

    ReactDOM.render(<Home header="Head description" />, document.getElementById('app'))

</script>

</html>

  Effect demonstration, input box after input content, click the button to pop up the input content

3, Pass from child to parent through refs

1. First create a method for the parent component to receive the data of the child component

2. refs is used in the method to change the content of the parent component element

3. In the method, the sub component uses this.props to obtain the method and call it

<script type="text/babel">
    // Parent component creation
    class Home extends React.Component {
        constructor(props) {
            super(props);
        }
        //The parent component creates a method to receive data from the child component
        getConentValue = (value) => {
            // After the method is executed, the value is changed through the element marked with refs
            this.refs.showMsg.innerHTML = value;
        }

        render() {
            return (
                // div must be added to the outermost layer of component nesting
                // Name showMsg after the ref tag on the element
                <div>
                    <Header title={this.props.header} getConentValue={this.getConentValue} ></Header>
                    <Content title={this.props.content} isLogin={this.props.isLogin} ></Content>
                    <Footer title={this.props.footer}></Footer>
                    <div ref="showMsg">Here, wait for the show content Contents of text box in</div>
                </div>
            )
        }
    }

    // Subcomponent creation
    class Header extends React.Component {
        constructor(props) {
            super(props);
        }
        //Subcomponent creation method
        getValue = () => {
            // Gets the input value of the subcomponent tag
            var value = this.refs.msg.value
            // Call the parent component method to transfer the child to the parent, and execute the parent component method to modify the ref element content of the parent component tag
            this.props.getConentValue(value);
        }
        render() {
            return (
                <div>
                    <input ref='msg' />
                    <h1 className="styleClass">{this.props.title}</h1>
                    <button onClick={this.getValue}>Click to get content</button>
                </div>
            )
        }
    }
    class Content extends React.Component {
        constructor(props) {
            super(props);
        }

        render() {
            // The sub component obtains data for judgment
            var button = null;
            if (this.props.isLogin == 1) {
                button = <button>Logged in</button>
            } else {
                button = <button>Not logged in</button>
            }
            //Store DOM elements into variables and use {} to display them dynamically
            return (
                <div>
                    {button}
                    <h2>{this.props.title}</h2>
                </div>
            )
        }
    }

    class Footer extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                list: [1, 2, 3]
            }
        }
        render() {
            // Use map to get each data in the list for rendering
            // key must be added for circular rendering, or an error may be reported
            var liList = this.state.list.map(function (item, index) {
                return <li key={index}>{item}</li>
            })
            return (
                <div >
                    <h1 className="styleClass">{this.props.title}</h1>
                    <ul>{liList}</ul>
                </div>
            )
        }
    }

    ReactDOM.render(<Home header="Head description" content='Content description' footer='Bottom description' isLogin='1' />, document.getElementById('app'))

</script>

  Before the button is clicked

  input, click the button to change the text

4, Son to son

1. The sub transmitter needs a bus for data storage and processing. In react, React.createContext() is a container for storing data and methods

This demonstrates the use of component separation writing. The normal framework can directly use import. I use html writing, so I can only use js files to import

bus.js Code: mainly used to store data and methods

//Create a unified data storage component
const ThemeContext = React.createContext('100');

home.js Code: parent component, the main page of the page, mapping JS, css and framework files

Use static to declare contextType in the parent component, and this.context can only be used in the component. In this way, you can obtain the default value of 100 after React.createContext('100 ').

Then, in the parent component render() page rendering, add ThemeContext.Provider to set data and operations.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app"></div>
</body>
<script src="./static/react.development.js"></script>
<script src="./static/react-dom.development.js"></script>
<script src="./static/babel.js"></script>
<script type="text/babel" src="./bus.js"></script>
<script type="text/babel">
    // Parent component creation
    class Home extends React.Component {
        constructor(props) {
            super(props);
        }

        //Use static to declare contextType. this.context can only be used in the component
        static contextType = ThemeContext;

        render() {
            //Gets the default value of 100 in createContext
            let num = this.context
            return (
                // div must be added to the outermost layer of component nesting
                // Apply and use the stored data tag. Provider to store values or methods in value
                <div>
                    <h1>Starting number{num}</h1>
                    <ThemeContext.Provider value={{
                        num,
                        add: function () {
                            this.num++
                        },
                        reduce: function () {
                            this.num--
                        }
                    }}>
                        <Child1></Child1>
                        <Child2></Child2>
                    </ThemeContext.Provider>
                </div>
            )
        }
    }
</script>
<script type="text/babel" src="./child1.js"></script>
<script type="text/babel" src="./child2.js"></script>
<script type="text/babel">
    ReactDOM.render(<Home />, document.getElementById('app'))
</script>

</html>

2. Pay attention to the import order of child components, which should be placed after the parent component.

In the subcomponent, you need to use static to declare contextType. this.context can only be used in the component, so that you can obtain the parameters and calculation methods in the bus

child1.js: subtract and get the result

class Child1 extends React.Component {
    constructor(props) {
        super(props);
    }
    //Use static to declare contextType. this.context can only be used in the component
    static contextType = ThemeContext;
    reduce = () => {
        //Get subtraction method in memory
        this.context.reduce();
        this.refs.reduceNum.innerHTML = 'Get the number after cutting' + this.context.num;
    }
    render() {
        return (
            <div>
                <button onClick={this.reduce} >subtraction</button>
                <div ref='reduceNum'>Get the number after cutting</div>
            </div>
        )
    }
}

child2.js: add and get the result

class Child2 extends React.Component {
    constructor(props) {
        super(props);
    }
    //Use static to declare contextType. this.context can only be used in the component
    static contextType = ThemeContext;
    add = () => {
        //Get addition method in memory
        this.context.add();
        this.refs.addNum.innerHTML = 'Add it to get the number' + this.context.num;
    }
    render() {
        return (
            <div>
                <button onClick={this.add} >addition</button>
                <div ref='addNum'>Add it to get the number</div>
            </div>
        )
    }
}

Page final result implementation

There are no numbers at first

  Click subtract to display 99

Click Add to add 1 to 99, which equals 100

 

 

Posted by subnet_rx on Fri, 08 Oct 2021 19:15:54 -0700