react简单组件

react简单组件效果如图

代码如下

//App是父组件 调用Add组件和List组件,所以将Add组件和List组件写在App的render()进行渲染

//App中的todos数组将会被Add组件和List组件公用,Add组件向todos数组添加数据和List组件将todos数组中的数据展示

    class App extends React.Component{

        constructor(props){

            super(props)

            this.state = {

                todos : ['吃饭','睡觉','打豆豆'],

            }

            this.addTodo = this.addTodo.bind(this)//绑定事件 必写 只要自己定义了函数就写一遍

        }

 

        addTodo(todo){

            const {todos} = this.state //获取原先的数组 可以直接写this.state.todos 效果一样

            todos.unshift(todo)         //添加数组

            this.setState({todos})    //更新数组值

        }

 

        render(){

            return(

                <div>

                    <h1>Simple Todo</h1>

                    <Add count = {this.state.todos.length} addTodo={this.addTodo}/>{/*向Add组件中传入todos数组长度,不仅可以传数也可以传函数*/}

                    <List todos={this.state.todos}/>{/*向List组件中传入todos数组中的数据*/}

                </div>

                

            )

        }

 

    }

    class Add extends React.Component{

        constructor(props){

            super(props)

            this.add = this.add.bind(this)//绑定事件 必写

        }

        add(){

            const todo = this.todoInput.value.trim() //获取到input中的value值

            if(!todo){

                return 

            }

            this.props.addTodo(todo)

            this.todoInput.value = ' '

        }

        render(){

            return(

                <div>

                    <input type="text" ref={input => this.todoInput=input}/>

                    <button onClick={this.add}>add #{this.props.count+1}</button>

                </div>

            )

        }

 

    }

    class List extends React.Component{

        render(){

            return(

                <ul>

                    {

                        this.props.todos.map((todo,index)=> <li key={index}>{todo}</li>)

                        //调用传入数据格式:this.props.传入原名

                        //用map函数遍历数组 

                    }

                </ul>

            )

        }

 

    } 

    List.propTypes = {

        todos : PropTypes.array.isRequired

    }//规定传入List组件数据的格式 

    Add.propTypes = {

        count : PropTypes.number.isRequired,

        addTodo : PropTypes.func.isRequired

    } //规定传入数据的格式和方法格式

 

    ReactDOM.render(<App/>,document.getElementById('test'))

 

 

问:如何在子组件中改变父组件的状态?

解决:子组件中不能直接改变父组件的状况,状态在那个组件,更新状态的行为就应该定义在那个组件。

           父组件定义函数,传递给子组件,子组件调用