react三大属性综合训练

2020-04-10  本文已影响0人  江江简书
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app"> </div>
</body>
<script type="text/javascript" src="../react.development.js"></script>
<script type="text/javascript" src="../react-dom.development.js"></script>
<script type="text/javascript" src="../babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
<script type="text/babel">
    //1.定义组件
    class App extends React.Component{
        //初始化
        constructor(props) {
            super(props);
            //定义状态
            this.state = {
                todos:["广州分公司","北京分公司","上海分公司"]
            }
            this.addTtodo = this.addTtodo.bind(this)
        }
        //定义一个方法让子组件调用
        addTtodo(todo){
            // console.log(this.state)
            let todos = this.state.todos
            todos.unshift(todo)
            // console.log(todos);
            this.setState({todos})
        }
        render (){
            return (
                <div>
                    <h2>测试React 三大属性</h2>
                    <Add addTtodo={this.addTtodo} />
                    <List todos={this.state.todos}  />
                </div>
            )
        }
    }
    //分离组件1.1
    class Add extends React.Component{
        constructor(props) {
            super(props);
            this.add = this.add.bind(this)
        }
        add(){
            const todo = this.todoInput.value;
            if(!todo){
                return false;
            }
            // console.log(todo);
            this.props.addTtodo(todo)
            this.todoInput.value = ''
        }
        render (){
            return <div>
                <input type="text" ref={input => this.todoInput=input} /> &nbsp;
                <button onClick={this.add}>添加内容</button>
            </div>
        }
    }
    //分离组件1.2
    class List extends React.Component{
        render(){
            let {todos} = this.props;
            return (
                <ul>
                    {todos.map((todos,index)=><li key={index}>{todos}</li>)}
                </ul>
            )
        }
    }
    // List.PropTypes = {
    //     todos:PropTypes.array.isRequired
    // }
    //2.渲染
    ReactDOM.render(<App />,document.getElementById('app'))
</script>
</html>

上一篇下一篇

猜你喜欢

热点阅读