gpt4 book ai didi

javascript - ReactJS 和继承

转载 作者:行者123 更新时间:2023-12-02 15:58:36 25 4
gpt4 key购买 nike

我正在尝试对分层组件实现删除功能。它是app.jsx>notes.jsx>note.jsx。这只是制作一个简单的待办事项列表,我按照教程进行操作。我已经用 babel 加载了它,但很难理解为什么这会删除整个待办事项列表而不是仅删除单个列表元素。

App.jsx:

import React from 'react';
import Note from './Note';
import Notes from './Notes';

export default class App extends React.Component {
constructor(props) {
super(props);

this.state = {
notes: [{
task: 'Learn webpacks'
}, {
task: 'Learn React'
}, {
task: 'Do laundry'
}]
};
}


render() {
var notes = this.state.notes;
return (
<div>
<button onClick= {()=>this.addItem()}> + </button>
<Notes items = {notes}
onEdit = {(i, task) => this.itemEdited(i, task)}
removeItem = {(i) => this.removeItem(i)}
/>

</div>
);
}

itemEdited(i, task) {
var notes = this.state.notes;

if(task) {
notes[i].task = task;
}
else {
notes = notes.slice(0, i).concat(notes.slice(i + 1));
}

this.setState({
notes: notes
});
}


addItem() {
this.setState({
notes : this.state.notes.concat([{
task : 'New Task'
}])

});
}

removeItem(i) {
var notes = this.state.notes;
this.setState({
notes : this.state.notes.slice(0, i)
});
}
}

Notes.jsx

import React from 'react';
import Note from './Note';

export default class Notes extends React.Component {
render() {
var notes = this.props.items;

return(
<ul className='notes'>{notes.map((note, i) =>
<li className = 'note' key = {'note' + i}>
<Note value = {note.task}
onEdit = {this.props.onEdit.bind(null, i)}
removeItem = {this.props.removeItem.bind(null, i)}
/>


</li>
)}</ul>
);
}
}

注释.jsx

import React from 'react';

export default class Note extends React.Component {

constructor(props) {
super(props);

this.state = {
edited: false
};
}

render() {
const {value, onEdit, ...props} = this.props;
var edited = this.state.edited;

return (
<div {...props}> {
edited
? <input type = 'text'
defaultValue = {value}
onBlur = {(e) => this.finishEdit(e)}
onKeyPress={(e) => this.checkEnter(e)}/>
: <div onClick={() => this.edit()}> {value} </div>
}
<button onClick = {(i) => this.props.removeItem(i
)}>-</button>
</div>

);
}

edit() {
this.setState({edited: true});
}

checkEnter(e) {
if(e.key === 'Enter') {
this.finishEdit(e);
}
}

finishEdit(e) {
this.props.onEdit(e.target.value);
this.setState({edited:false});
}



}

一切正常,但删除单个列表元素,而不是删除该元素,而是删除整个列表。我认为这与传递removeItem的逻辑有关,但我不知道到底要传递什么。在我看来,note 是单独的 note/list 元素,因此为了删除它,函数必须向下滴入此类,正确吗?

编辑:尝试我认为它应该如何工作。

最佳答案

出了问题的是1:未将 null 绑定(bind)到 this.props.removeItem.bind(i)

其次,当我打算拼接它时,我正在切片整个东西,但我只是这样做了:

removeItem(i) {
var notes = this.state.notes;
notes = notes.slice(0, i).concat(notes.slice(i + 1));
this.setState({
notes : notes
});
}

获取该列表之前的所有元素并将其与之后的所有元素连接起来。虽然 Notes = Notes.splice(i, 1) 也应该正确工作?我尝试过,但它会删除除该元素之外的所有内容。

关于javascript - ReactJS 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com