# 多种实现双向绑定方法

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

<!DOCTYPE html>
<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>

    <!-- react挂载的位置 -->
    <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>

在这里插入图片描述

Last Updated: 7/15/2020, 10:34:45 PM