最基本的一个todolist,涉及基本的组件通信。效果如下:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import TodoList from './TodoList';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<TodoList />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
TodoList.js
import React,{Component,Fragment} from 'react';
import TodoItem from './TodoItem';
import Test from './Test';
class TodoList extends Component{
// 当组件的state或者props发生改变时,render函数会重新执行
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);
}
componentWillMount(){
// console.log('componentWillMount');
}
render(){
// console.log('render');
return (
<Fragment>
<div>
<label htmlFor="insertArea">输入内容</label>
<input
id="insertArea"
value={this.state.inputValue}
onChange={this.handleInputChange}
ref={(input)=>{this.input = input}}
/>
<button onClick={this.handleBtnClick}>提交</button>
</div>
<ul>
{
this.getTodoItem()
}
</ul>
{/* <Test content={this.state.inputValue}/> */}
</Fragment>
)
}
getTodoItem(){
return this.state.list.map((item,index)=>{
return(
<div key={index}>
<TodoItem
content = {item}
index = {index}
deleteItem = {this.handleItemDelete}
/>
</div>
)
})
}
handleInputChange(e){
// const value = e.target.value; // 使用setState异步函数赋值必须将e.target值提前赋值,不然会报错
const value = this.input.value;
this.setState(()=>({
// inputValue:e.target.value
inputValue:value
}));
}
handleBtnClick(){
this.setState((prevState)=>({
list:[...prevState.list,prevState.inputValue], //数组追加元素
inputValue:''
}));
}
handleItemDelete(index){
this.setState((prevState)=>{
const list = [...prevState.list];
list.splice(index,1);
return {
list
}
});
}
}
export default TodoList;
TodoItem.js
import React,{Component} from 'react';
class TodoItem extends Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
shouldComponentUpdate(nextProps,nextState){
if(nextProps.content !== this.props.content){
return true;
}else{
return false;
}
}
render(){
console.log('TodoItem render');
const {content} = this.props ;
return(
<div
onClick={this.handleClick}
dangerouslySetInnerHTML={{__html:content}}
/>
)
}
handleClick(){
const {deleteItem,index} = this.props ;
deleteItem(index);
}
}
export default TodoItem;
代码链接:
链接:https://pan.baidu.com/s/1HKikCZontl2wQig1oXKc8Q
提取码:hghn
复制这段内容后打开百度网盘手机App,操作更方便哦--来自百度网盘超级会员V5的分享