react 组合组件

时间:2020-05-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="test">

</div>

<script src="js/react.development.js"></script>
<script src="js/react-dom.development.js"></script>
<script src="js/babel.min.js"></script>
<script src="js/prop-types.js"></script>

<script type="text/babel">
    // 创建组件
    class AppConponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                data: ['php', 'java', 'js']
            };

            this.handleAdd = this.handleAdd.bind(this);
        }

        /**
         * 添加数据
         * @param tmp
         */
        handleAdd(tmp){
            let {data} = this.state;
            data.unshift(tmp);
            this.setState({data});
        }

        render() {
            return (
                <div>
                    <InputConponent handleAdd={this.handleAdd}/>
                    <ShowConponent data={this.state.data}/>
                </div>
            );
        }
    }

    // 添加组件
    class InputConponent extends React.Component {
        constructor(props) {
            super(props);
            this.handleClick = this.handleClick.bind(this);
        }

        handleClick(){
            let tmp = this.addInput.value.trim();
            if (tmp){
                this.props.handleAdd(tmp);
            }
            this.addInput.value = '';
        }

        render() {
            return (
                <div>
                    <input type="text" ref={input => this.addInput = input}/>
                    <button onClick={this.handleClick}>添加</button>
                </div>
            );
        }
    }

    // 显示组件
    class ShowConponent extends React.Component {
        constructor(props) {
            super(props);
        }

        render() {
            return (
                <ul>
                    {this.props.data.map((item,index) => <li key={index}>{item}</li>)}
                </ul>
            );
        }
    }


    // 渲染虚拟dom
    ReactDOM.render(<AppConponent/>, document.getElementById('test'));
</script>
</body>
</html>