更多的是概念问题,而不是错误修复。
我反应还很陌生,并且正在尝试使用添加和删除功能构建一个简单的待办事项应用程序。我实现了一项功能,只要单击待办事项列表元素,它就会被删除。我用CSS设置了样式并为其加上边框。
这里的主要问题是,每当我单击列表的元素时,它就会消失,但边框仍然保留。只是文本分配器,而不是整个div。
这是App.js代码
import React, { Component } from 'react';
import './App.css';
import Navbar from './Navbar/Navbar'
import InputBox from './inputBox/inputBox';
import ListTodo from './listTodo/listTodo';
class App extends Component {
constructor(props){
super(props)
console.log("This is from the constuor");
this.state={
todo:[
],
temp:''
}
}
changed=(thing)=>{
var x = thing.target.value;
this.setState({
temp:x
})
}
addTodo = ()=>{
const item = [
...this.state.todo
]
item.push(this.state.temp);
this.setState({
todo:item
})
}
removeIt = (index)=>{
const item = [
...this.state.todo
]
delete item[index]
this.setState({
todo:item
})
}
render() {
return (
<div className="change">
<Navbar/>
<InputBox
changed={(event)=>this.changed(event)}
addTodo = {this.addTodo}
/>
<ListTodo
todoList = {this.state.todo}
removeIt = {this.removeIt}
/>
</div>
);
}
}
export default App;
我的inputBox组件:
import React from 'react';
import {Button} from 'react-bootstrap';
import './inputBox.css'
const inputBox = (props)=>{
const keyPress=(e)=>{
if(e.keyCode === 13){
console.log('value', e.target.value);
props.addTodo();
}
}
return(
<div className="center">
<input className="inputDis" type="text" key='1' onChange={props.changed} onKeyDown={keyPress}/>
<Button className="buttonDis" bsStyle="info" key='2' onClick={props.addTodo}>Info</Button>
</div>
)
}
export default inputBox
我的待办事项列表组件:
import React from 'react';
import {Button} from 'react-bootstrap';
import './listTodo.css'
const displayTodo = (props)=>{
const items = props.todoList.map((item, index)=>{
return(
<div key={index+"upper"} onClick={()=>props.removeIt(index)} className="listTodo">
<span key={index+"div"}>{item}</span>
{/* <Button onClick={()=>props.removeIt(index)} bsStyle="info" key='remove'>X</Button> */}
</div>
)})
return (
<div>{items}</div>
);
}
export default displayTodo
答案 0 :(得分:3)
问题是您的removeIt
代码,您需要复制所有元素,然后删除特定索引处的值,使其保持未定义状态(有一个空洞),因此它由todoList.map...
呈现
removeIt = (index)=>{
const item = [
...this.state.todo
]
delete item[index]
this.setState({
todo:item
})
}
常见的约定是过滤索引不等于要删除的元素的所有元素
removeIt = (index)=>{
const newItems = this.state.items.filter((el, elIndex) => elIndex !== index);
this.setState({
todo: newItems
})
}
const data = [1,2,3,4,5,6];
// delete method
const data1 = [...data];
delete data1[3]; // delete index 3
console.log(data1); // [1,2,3,undefined,5,6]
// filter method
const data2 = [...data].filter((el, index) => index !==3); // filter index 3 out
console.log(data2); // [1,2,3,5,6]