一、TodoList實現列表添加刪除功能
添加webpack命令: yarn add webpack
創建components 目錄及TodoList.js
pages 目錄創建 show用來渲染TodoList組件
TodoList.js 代碼
import React,{ Component } from 'react';
//Fragment 隱藏外層標籤
class TodoList extends Component{
//調用父類Component的構造函數,固定寫法。
constructor(props){
super(props);
//創建數據
this.state={
inputValue:'hello',
list:['學習React','學習前端']
}
}
render() {
return (
<div>
{/*jsx語法,有提示。bind 改變this指向爲調用的函數 */}
<input onChange={this.handleInputChange.bind(this)} value={this.state.inputValue}/>
<button onClick={this.handleBtnClick.bind(this)}>提交</button>
<ul>
{
// 循環輸出list
this.state.list.map((item,index)=>{
return (
<li onClick={this.handleItemDelete.bind(this,index)} key={index}>
{item}
</li>
)
})
}
</ul>
</div>
)
}
handleInputChange(e){
this.setState({
inputValue:e.target.value
})
}
//添加
handleBtnClick(){
this.setState({
//展開運算符,拿到以前數組的內容,生成新的數組。
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
//刪除 index爲下標
handleItemDelete(index){
const list=[...this.state.list];
//刪除一個下標爲index的值
list.splice(index,1);
this.setState({
list:list
})
}
}
export default TodoList;
show.js 代碼
import React from 'react';
import TodoList from '../components/TodoList';
export default function() {
return (
<div>
<TodoList></TodoList>
</div>
);
}
測試
點擊按鈕可以增加,點擊文字可以刪除。
二、拆分組件修改功能
創建 TodoItem.js 通過this.props.content獲取父組件傳遞的內容
import React,{ Component } from 'react';
class TodoItem extends Component{
constructor(props){
super(props);
this.handleClick=this.handleClick.bind(this);
}
render() {
return (
<div onClick={this.handleClick}>
{this.props.content}
</div>
)
}
handleClick(){
this.props.deleteItem(this.props.index)
}
}
export default TodoItem;
TodoList.js 引入子組件
import React,{ Component } from 'react';
import TodoItem from "@/components/TodoItem";
//Fragment 隱藏外層標籤
class TodoList extends Component{
//調用父類Component的構造函數,固定寫法。
constructor(props){
super(props);
//創建數據
this.state={
inputValue:'hello',
list:['學習React','學習前端']
}
}
render() {
return (
<div>
{/*jsx語法,有提示。bind 改變this指向爲調用的函數 */}
<input onChange={this.handleInputChange.bind(this)} value={this.state.inputValue}/>
<button onClick={this.handleBtnClick.bind(this)}>提交</button>
<ul>
{
// 循環輸出list
this.state.list.map((item,index)=>{
return (
<div>
{/*組件內容傳遞*/}
<TodoItem content={item} index={index} deleteItem={this.handleItemDelete.bind(this)}/>
{/*<li onClick={this.handleItemDelete.bind(this,index)} key={index}>*/}
{/*{item}*/}
{/*</li>*/}
</div>
)
})
}
</ul>
</div>
)
}
handleInputChange(e){
this.setState({
inputValue:e.target.value
})
}
//添加
handleBtnClick(){
this.setState({
//展開運算符,拿到以前數組的內容,生成新的數組。
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
//刪除 index爲下標
handleItemDelete(index){
const list=[...this.state.list];
//刪除一個下標爲index的值
list.splice(index,1);
this.setState({
list:list
})
}
}
export default TodoList;