react 學習--使用Mixin

xiaopengyaonixi發表於2016-10-25
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
    var BindingMixin = {
        handleChange:function (key) {
            var that = this;
            var newState = {};
            return function (event) {
                newState[key] = event.target.value;
                that.setState(newState)
            }
        }
    }

    var BindingExample = React.createClass({
        mixins:[BindingMixin],
        getInitialState:function () {
            return {
                text:'',
                comment:''
            };
        },
        render:function () {
            return (
                    <div>
                        <input type="text" placeholder="請輸入內容" onChange={this.handleChange('text')}/>
                        <br/>
                        <textarea onChange={this.handleChange('comment')}>
                        </textarea>
                        <p>{this.state.text}</p>
                        <p>{this.state.comment}</p>
                    </div>
            );
        }
    });
    ReactDOM.render(<BindingExample/>,document.getElementById("app"));
</script>
</body>
</html>

相關文章