2019独角兽企业重金招聘Python工程师标准>>>
TodoList.js
import React, { Component, Fragment } from 'react'
import TodoItem from './TodoListItem'
import './style.css'
class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list: []
}
this.handleInputChange = this.handleInputChange.bind(this)
this.handleKeyDown = this.handleKeyDown.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
this.handleItemDelete = this.handleItemDelete.bind(this)
}
render() {
return (
{
/**这是注释,在html中
* 用htmlFor代替for,
* 用className代替class
* 来避免和JS的相关关键字冲突*/
}
{this.getTodoItem()}
)
}
getTodoItem() {
return this.state.list.map((item, index) => {
return (
)
})
}
handleInputChange(e) {
const value = e.target.value
this.setState(() => ({
inputValue: value
}))
}
handleBtnClick() {
/**不能直接操作state中的数据,
* 如果用this.state.list.push(this.state.inputValue)会报错
* 最好是使用ES6中的展开运算符
* list: [...this.state.list, this.state.inputValue],
* 同步的写法
* this.setState({
* list: [...this.state.list, this.state.inputValue],
* inputValue: ''
* })
* 推荐异步的写法*/
this.setState((prevState) => ({
list: [...prevState.list, prevState.inputValue],
inputValue: ''
}))
}
handleItemDelete(index) {
/**immutable规范
* state不允许直接改变,会影响性能优化*/
const list = [...this.state.list]
list.splice(index, 1);
this.setState({
list: list
})
}
handleKeyDown(e) {
if (e.keyCode === 13)
this.handleBtnClick()
}
}
export default TodoList
TodoItem.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class TodoItem extends Component {
constructor(props) {
/**当组件的state或props发生改变的时候
* render函数就会重新执行*/
super(props)
this.handleItemClick = this.handleItemClick.bind(this)
}
render() {
const { item } = this.props
return (
{item}
)
}
handleItemClick() {
const { deleteItem, index } = this.props
deleteItem(index)
}
}
/**属性校验 */
TodoItem.propTypes = {
item: PropTypes.string.isRequired,//必传
deleteItem: PropTypes.func,
index: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
}
/**为属性设置默认值 */
TodoItem.defaultProps = {
test: 'hello world'
}
export default TodoItem
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
ReactDOM.render( , document.getElementById('root'));