react组件属性综合运用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38323645/article/details/83317661
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>07_state_demo</title>
</head>
<body>
  <div>
    <h2>Simple TODO List</h2>
    <input type="text">
    <button>Add #4</button>
    <ul>
      <li>吃饭</li>
      <li>写代码</li>
      <li>读书</li>
    </ul>
  </div>
  <hr>

  <div id="example"></div>

  <script src="../js/react.js"></script>
  <script src="../js/react-dom.js"></script>
  <script src="../js/babel.min.js"></script>
  <script type="text/babel">
    //组件1  嵌套了组件2和组件3
    class App extends React.Component{
        constructor(props){
            super();
            //初始化状态
            this.state = {
                todos:['吃饭','写代码','读书']
            };
            //修改add的this指向
            this.add = this.add.bind(this);
        }
        add(newdo){
          let todos = this.state.todos;
          todos.unshift(newdo);//添加元素到原先数组里面
            //更新状态(重新渲染)
            this.setState({
                todos : todos//同名属性可以不写,即这里只写一个todos就可以
            });
        }
        render () {
            let {todos} = this.state;
            return (
                    <div>
                      <AddTodo add={this.add} length={todos.length}/>
                      <TodoList todosss={todos} />
                    </div>
            )
        }
    }
    //组件2
    class AddTodo extends React.Component{
        constructor(props){
            super();
            this.myclick = this.myclick.bind(this);
        }
       myclick(){
       let newdo = this.refs.newdo.value;
       if(!newdo.trim()){
         alert("输入内容不能为空");
         return ;
       }
       //调用父组件方法
        this.props.add(newdo);
        //清空输入框值
         this.refs.newdo.value = '';
       }
        render () {
            return (
                    <div>
                      <input  ref="newdo"type="text"/>
                        <button onClick={this.myclick}>Add #{this.props.length}</button>
                    </div>
            )
        }
    }
    //组件3
    class TodoList extends React.Component{
        render () {
            let {todosss} = this.props;
            return (
                   <ul>
                       {
                           todosss.map((item,index) => <li key={index}>{item}</li>)
                       }
                   </ul>
            )
        }
    }

    ReactDOM.render(<App />,document.getElementById("example"));
  </script>
</body>
</html>

运行效果
在这里插入图片描述
输入值点击add按钮后:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38323645/article/details/83317661