gpt4 book ai didi

javascript - 如何使用 react 过滤数据?

转载 作者:行者123 更新时间:2023-11-30 07:12:15 26 4
gpt4 key购买 nike

我已经创建了搜索过滤器,但我无法在搜索输入中输入任何内容,这是为什么?我已经创建了 searchTermChanged 方法,但为什么它不起作用?当用户在输入字段中键入时,项目应该根据标题进行过滤。

代码:

    import Projects from '../../data/projects';

export default class Home extends Component {

constructor(props) {
super(props);
this.state = {
search: '',
projects: Projects
}
}

searchTermChanged = (event) => {
this.setState({ projects: this.state.projects.filter(val =>
val.title.toLowerCase().indexOf(this.state.search.toLowerCase()) > -1 )
})
}

render() {
return (
<div>
<div className="header">
<div className="md-form mt-0 customsearch">
<input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
value={this.state.search}
onChange={e => this.searchTermChanged(e.target.value)}
/>
</div>
</div>
<div class="container-fluid">
<div class="row">
{this.state.projects.map((val,index) => (
<div class="col-3">
<Card title={val.title} by={val.by} blurb={val.blurb}
url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>
</div>
))}
</div>
</div>
</div>
)
}
}

最佳答案

您需要确保正确使用状态。

import Projects from '../../data/projects';

export default class Home extends Component {

constructor(props) {
super(props);
this.state = {
search: '',
projects: Projects
}
}

searchTermChanged = (search) => {
this.setState({
//Update the search state here.
search,
//Use the current search state to filter
projects: this.state.projects.filter(val =>
val.title.toLowerCase().indexOf(search.toLowerCase()) > -1 )
}
);
}

render() {
return (
<div>
<div className="header">
<div className="md-form mt-0 customsearch">
<input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
value={this.state.search}
onChange={e => this.searchTermChanged(e.target.value)}
/>
</div>
</div>
<div class="container-fluid">
<div class="row">
{this.state.projects.map((val,index) => (
<div class="col-3">
<Card title={val.title} by={val.by} blurb={val.blurb}
url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>
</div>
))}
</div>
</div>
</div>
)
}
}

关于javascript - 如何使用 react 过滤数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53946043/

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