楼主这里。因为我现在对React的了解更多,而且这篇文章还有人查看,所以我想用我现在的知识更新一下。
SavedSearches.js
import React from 'react'
import { SearchList } from './SearchList'
let data = [
{index: 0, name: "a string", url: 'test.com/?search=string'},
{index: 1, name: "a name", url: 'test.com/?search=name'},
{index: 2, name: "return all", url: 'test.com/?search=all'}
];
let startingIndex = data.length;
export class SavedSearches extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
url: '',
index: startingIndex,
data: data
}
this.deleteSearch=this.deleteSearch.bind(this)
}
deleteSearch(deleteThis) {
console.log(deleteThis);
let newData = this.state.data.filter( searchItem => searchItem.index !== deleteThis.index )
this.setState({
data: newData
})
}
render() {
return (
<div className="search-container">
<SearchList data={this.state.data} onDelete={this.deleteSearch}/>
</div>
)
}
}
这里我创建了一个名为deleteSearch
的方法,它以一个对象作为参数。然后在this.state.data
数组上运行.filter
,创建一个新数组,包含不符合条件的所有项。条件检查数据数组中每个对象的id是否与参数的id匹配。如果是,则该对象将被删除。由.filter
创建的新数组设置为一个名为newData
的变量,然后使用newData
数组更新状态。
然后我将这个方法通过一个名为onDelete
的prop传递给SearchList
组件。
在构造函数中,还使用.bind()
绑定了这个方法,以便在方法传递到组件树时,this
将引用正确的this
。
SearchList.js
import React from 'react'
import { SearchItem } from './SearchItem'
export class SearchList extends React.Component {
render() {
let searchItems = this.props.data.map((item, i) => {
return (
<SearchItem index={i} searchItem={item} url={item.url} onDelete={this.props.onDelete}>
{item.name}
</SearchItem>
);
});
return (
<ul>
{searchItems}
</ul>
);
}
}
我的deleteSearch
方法只是在这里通过组件树传递。 SearchList
以props的形式接收该方法this.props.onDelete
并将其传递给SearchItem
。
另一个主要关键点是map函数中的参数被作为props传递:searchItem={item}
。 这将允许通过props访问整个当前对象;如果您记得,我的deleteSearch
函数以对象作为参数。
SearchItem.js
import React from 'react'
export class SearchItem extends React.Component {
constructor(props) {
super(props);
this.handleDelete=this.handleDelete.bind(this)
}
handleDelete() {
this.props.onDelete(this.props.searchItem)
}
render() {
return (
<li key={this.props.index}> {/* Still getting a console error over this key */}
<a href={this.props.url} title={this.props.name}>
{this.props.children}
</a>
({this.props.url})
<button onClick={this.handleDelete} value={this.props.index}><i className="fa fa-times"></i>
</button>
</li>
);
}
};
现在我的方法到达了它将要被使用的地方。我创建一个处理程序方法
handleDelete
,在其中使用
this.props.onDelete
访问
deleteSearch
方法。然后,我使用
this.props.searchItem
向它传递正在单击的列表项的对象。
为了使用户单击时这个方法能够起作用,我必须添加一个调用我的处理程序方法的
onClick
事件监听器,如下所示:
onClick={this.handleDelete}
。最后一步是在
SearchItem
构造函数方法中绑定
this.handleDelete
。
现在,单击按钮将从
this.state.data
数组中删除该项。有关如何向数组中添加项的示例,请参见我的
存储库。
onClick={this.props.deleteSearchItem}
这样的语法对我来说很有帮助,因为我是新手。 - Virge Assault