[英]React todo app, problem with removing task
I'm working on todo app in React and I have weird problem.我正在使用 React 开发 todo 应用程序,但我遇到了奇怪的问题。 I created onClick effect on trash icon to remove whole task component.
我在垃圾桶图标上创建了 onClick 效果以删除整个任务组件。 The thing is, sometimes it works (removes whole task), sometimes not (removes only icon).
问题是,有时它有效(删除整个任务),有时无效(仅删除图标)。 I tried different solutions but to be honest I have no idea why it works like this, this is the same script working differently in different components, for some reason.
我尝试了不同的解决方案,但老实说,我不知道它为什么会这样工作,这是同一个脚本在不同的组件中工作方式不同,出于某种原因。
main component:主要成分:
import React from 'react'
import TaskContainer from './TaskContainer.js';
import SingleTask from './SingleTask'
class AppContainer extends React.Component {
constructor(props) {
super(props)
this.state = {
children: [],
numChildren: 0,
newMessage: "What to do next?"
}
this.onAddChild = this.onAddChild.bind(this)
this.handleChange = this.handleChange.bind(this)
}
onAddChild = (msg) => {
let newArray = this.state.children.concat(<SingleTask message={msg} />);
this.setState({ children: newArray });
console.log(this.state.children)
}
handleChange(event) {
this.setState({ newMessage: event.target.value })
}
render() {
return (
<div className="app-container">
<div className="new-task-container">
<input type="text" id="taskInput" defaultValue="What to do next?"
maxlength="50" onChange={this.handleChange} />
<div className="addTask" id="addTask" onClick={
() => {
let text = document.getElementById("taskInput").value;
this.setState({ newMessage: text })
this.onAddChild(this.state.newMessage);
}
}>
<div className="add-button">Add task</div>
</div>
</div>
<TaskContainer>
{this.state.children}
</TaskContainer>
</div>
)
}
}
export default AppContainer
child component子组件
import SingleTask from './SingleTask.js';
function TaskContainer(props) {
return (
<div className="task-container">
{props.children}
</div>
)
}
export default TaskContainer
child's child component - SingleTask child 的子组件 - SingleTask
import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTrashAlt } from '@fortawesome/free-regular-svg-icons'
class SingleTask extends React.Component {
constructor(props) {
super(props)
this.state = { active: true }
}
render() {
return (
<div className="singleTask" >
<p>{this.props.message}</p>
<div className="removeTask" onClick={(event) => {
setTimeout(() => {
event.target.parentNode.parentNode.remove()
}, 350)
}
}>
<FontAwesomeIcon icon={faTrashAlt} />
</div>
</div>
)
}
}
export default SingleTask
thanks in advance提前致谢
I create a CodeSandbox with all the necessary corrections.我创建了一个包含所有必要更正的 CodeSandbox。
https://codesandbox.io/s/upbeat-jang-v7jvm https://codesandbox.io/s/upbeat-jang-v7jvm
Piece of advice: When using React is not recommend that you modify the DOM by yourself.忠告:在使用 React 的时候不建议自己修改 DOM。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.