多种方式实现双向绑定

我们使用两种方式来实现双向绑定的:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>双向绑定title>

    
    <input id="input" type="text" />
    <div id="text">div>

    
    <div id="app">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.原生js实现双向绑定
        let input = document.getElementById("input");
        let text = document.getElementById("text");
        let data = {
            value: ""
        };
        Object.defineProperty(data, "value", {
            set: function (val) {
                text.innerHTML = val;
                input.value = val;
            },
            get: function () {
                return input.value;
            }
        });
        input.onkeyup = function (e) {
            data.value = e.target.value;
        };

        //2.react实现双向绑定
        class Com extends React.Component {
            constructor(props){
                super(props)
                this.state={
                    msg:''
                }
            }
            render(){
                return(<div>
                            <input onKeyUp={this.inputChange} />
                            <div>{this.state.msg}</div>
                        </div>
                )
            }
            inputChange=(e)=>{
                this.setState({
                    msg:e.target.value
                })
            }
        }
        ReactDOM.render(<Com />,document.getElementById('app'))
    script>
head>
<body>
body>
html>

多种方式实现双向绑定_第1张图片

你可能感兴趣的:(笔记,vue,react,js)