在这里。由于四年后我对 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 创建的新数组设置为名为@987654327@ 的变量,然后我使用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 函数中的参数作为道具传递: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 数组中删除该项目。有关如何向数组中添加项目的示例,请参阅我的repository