我有一个 <select>
<option>
在哪里是动态生成的。此外还有一个 <input>
当用户键入时,它会匹配过滤掉 <option>
数量的字符.所以如果<input>
是空白的,它返回完整列表,并且会有一条消息说 116 Results Found
.当他们键入“head”时,它将更新为 8 Results Found
.很常见的事情。
我不知道如何得到计数。我正在尝试在 _.map
中做一些事情这很重要i++
然后 this.setState({ count: i })
;然而,这基本上会使浏览器变砖,因为它陷入了无限循环(嗯,在我强行关闭它之前它会产生数千个相同的错误,因为浏览器在计算时被锁定)。
另一个想法是计算 <option>
的数量。元素,但我不知道如何实现它。
有什么建议吗?
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
class BasicQuery extends Component {
constructor(props) {
super(props);
this.state = {
term: '',
count: ''
};
}
onInputChange(term) {
this.setState({ term });
}
renderOptionsSelect(term) {
var filterTerm = this.state.term.toLowerCase();
var i = 0;
return _.map(this.props.pos_list, p => {
if (p.pos_code.toLowerCase().match(filterTerm)) {
i++;
return (<option key={p.pos_code} value={p.pos_code}>{p.pos_code}</option>);
}
this.setState({ count: i });
});
}
// render the main element of the container
render() {
return (
<div className='panel panel-default'>
<div className='panel-heading'>
<h4><strong>Basic Query</strong></h4>
</div>
<div className='panel-body'>
<input
className='form-control'
placeholder='Enter Keyword or Position Code'
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)}
/>
<hr />
<h4>Position:</h4>
<select className='form-control'>
<option></option>
{this.renderOptionsSelect()}
</select>
<br />
<h4>Data Cut:</h4>
<select className='form-control' disabled={true} />
</div>
</div>
);
}
}
// map the state in the Redux store to props
function mapStateToProps(state) {
return {
results: state.results.results,
pos_list: state.results.pos_list
}
}
export default connect (mapStateToProps, null)(BasicQuery);
最佳答案
我会这样做:
onInputChange(term) {
const filterTerm = term.toLowerCase();
const filteredItems = this.props.pos_list.filter( p =>
p.pos_code.toLowerCase().match(filterTerm)
)
this.setState({
term,
filteredItems,
count: filteredItems.length
});
}
然后在渲染中:
this.state.filteredItems.map( p =>
<option key={p.pos_code} value={p.pos_code}>{p.pos_code}</option>
)
关于javascript - 尝试获取 <option> 的计数,因为它在 React 应用程序中被过滤掉了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48234029/