美文网首页
react三大属性综合训练

react三大属性综合训练

作者: 江江简书 | 来源:发表于2020-04-10 20:43 被阅读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>
    
    

    相关文章

      网友评论

          本文标题:react三大属性综合训练

          本文链接:https://www.haomeiwen.com/subject/wttkmhtx.html