在 Angular JS 中,我发现了 ng-repeat 的“过滤器”选项,它随实时搜索一起提供。例如:
<div ng-repeat="std in stdData | filter:search">
<!--
Std Items go here.
-->
</div>
<input type="text" placeholder="Search std items" ng-model="search.$" />
这样我们在搜索框中键入的任何项目都会被过滤。我想知道 React JS 中是否有任何替代功能?
最佳答案
React 没有开箱即用的解决方案。
但是,您可以创建自己的搜索框。请参阅以下示例。
该代码段已通过评论进行了很好的处理。这应该对你有帮助。
class Search extends React.Component{
constructor(props){
super(props)
this.state = {
items: ['car', 'mango', 'stackoverflow', 'computer'], //declare the items to be listed
searchTerm: null //initial search term will be null
}
this.onChange = this.onChange.bind(this)
}
onChange(e){
this.setState({
searchTerm: e.target.value //set the new serah term to the state
})
}
render(){
const items = this.state.items.map((item)=>{
if(!this.state.searchTerm) return <div>{item}</div> //return the items without filter when searchterm is empty
const regEx = new RegExp(this.state.searchTerm, 'g') //create regex based on search term to filter the items
return regEx.test(item) && <div>{item}</div> //if the item passes the regex text, return that item
})
return <div>
<input type="text" onChange={this.onChange} placeholder='search'/>
<div>
{items}
</div>
</div>
}
}
ReactDOM.render(<Search/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
关于javascript - React JS 中的 Angular JS ng-repeat 过滤器替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40223854/