首页 > IT职业 > IT图书 > 从0开发简书项目(3)-优化todoList功能
定义css的类的时候,不能用class,要用className来代替class这个关键词,因为我们用class已经声明类了,这样会重复定义。
注释的话用{}
点击label获取input的光标,可以在input上定义一个id,比如这个id是insertArea,那么在label中加htmlFor。代替之前的for 关键字。
在import React, { Component },这里的{ Component}是结构赋值。
react是树形的结构,这里todoList是大组件,todoItem是todoList下的小组件。
父组件向字组件传递数据用属性才进行传递,通过标签属性传递(属性和方法)过去之后,子组件用this.props.*来进行接收。
子组件如何调用父组件的方法,并改变里面的数据?把父组件的方法传给子组件即可。用this.props.*,父组件如果传递方法,需要做一次绑定。
要不然会出现下面的错误:TypeError: Cannot read property 'list' of undefined
// index.jsimport React from 'react';import ReactDOM from 'react-dom';import TodoList from './TodoList'; ReactDOM.render(, document.getElementById('root'));
//TodoList.jsimport React, { Component, Fragment } from 'react';import TodoItem from './TodoItem';class TodoList extends Component { constructor(props) { super(props) this.state = { inputValue: '', list: []
} this.handleInputChange = this.handleInputChange.bind(this); this.handleBtnClick = this.handleBtnClick.bind(this); this.handleItemDelete = this.handleItemDelete.bind(this);
}
handleInputChange (e) { const value = e.target.value this.setState(() => ({ inputValue: value
})) // old
// this.setState({
// inputValue: e.target.value
// })
}
handleBtnClick() { //setState有一个参数可以接收以前的数据
this.setState((prevState) => ({ list: [...prevState.list, prevState.inputValue], inputValue: ''
})) // old
// this.setState({
// list: [...this.state.list, this.state.inputValue],
// inputValue: ''
// })
}
handleItemDelete (index) { // immutable
// state 不允许我们做任何改变
this.setState((prevState) => { const list = [...prevState.list]
list.splice(index, 1); return {list}
});
}
getTodoItem () { return this.state.list.map((item, index) => { return (
)
})
}
render() {
return (
{this.getTodoItem()}
)
}
}
export default TodoList; //把自身导出,外部才可以引用。
//TodoItem.jsimport React, { Component } from 'react';class TodoItem extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this);
}
handleClick() { const { deleteItem ,index } = this.props
deleteItem(index);
}
render() { const { content } = this.props return (
{content}
)
}
}export default TodoItem;
直接操作dom的开发方式是命令式开发的方式,比如我们熟悉的jquery
而react是声明式开发 可以与其他框架并存 组件式开发
react是单向数据流,只允许父组件向子组件传递数据,子组件绝对不能修改父组件传递的数据,而必须要删除的话是子组件调用父组件的方法,然后进行删除,这里实际上也是调用对父组件进行操作,这样只需要维护父组件即可,维护起来比较容易
react是一个视图层框架,小型项目即可。而大型的需要依赖Flux redux等这样的数据层框架
函数式编程,都是一个一个的函数组成,方便于测试,给前端的自动化测试带来很大的便捷性。
以上。
作者:程序员小哥哥
链接:https://www.jianshu.com/p/b0e7f8ec27d9
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4648/viewspace-2814456/ ,如需转载,请注明出处,否则将追究法律责任。