这可能是一个克隆帖子,但我在我的情况下没有找到任何解决方案。我有一组对象:
export default function() {
return [
{name: 'Mark Teer Stegen'},
{name: 'Nelson Semedo'},
{name: 'Gerrard Pique'},
{name: 'Ivan Rakitic'},
{name: 'Sergio Busquets'},
{name: 'Denis Suarez'},
{name: 'Coutinho'},
{name: 'Luis Suarez'},
{name: 'Lionel Messi'},
{name: 'Dembele'},
{name: 'Malcom'}
]
}
我将其导入到组件中,赋值给状态并在下面的组件中显示。
import React, {Component} from 'react';
import {connect} from 'react-redux';
class Barca extends Component{
constructor(props){
super(props);
this.state = {
players: this.props.players,
player: '' //empty to set as an input
}
}
onChange(e){
this.setState({
player: e.target.value
});
console.log(this.state.player);
}
renderList(){
return this.state.players.map((player) => {
return(
<tr key={player.name}>
<td>{player.name}</td>
</tr>
);
});
}
render(){
return(
<div className="col-sm-6 table-col table-responsive">
<input
type="text"
value={this.state.player}
onChange={this.onChange.bind(this)}
/>
<table className="table table-striped">
<thead>
<tr>
<th className="text-center">
FC Barcelona
</th>
</tr>
</thead>
<tbody>
{this.renderList()}
</tbody>
</table>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
players: state.reducerBarca
};
};
export default connect(mapStateToProps)(Barca);
列表看起来像这样
问题在于我想根据输入值过滤我的玩家列表。我在这里进行了一些研究,我只发现可以在数组中过滤,而不是像对象列表中那样。
我现在所做的:
- 显示玩家列表
- 获取输入框中的值,并在每次输入后显示它
- 如何通过输入的条件渲染我的列表?
感谢大家!我已删除了玩家状态
constructor(props){
super(props);
this.state = {
//players: this.props.players <-- Stupid thing
player: '' //empty to set as an input
}
}
并且重写我的renderList()
函数
return this.props.players.filter(player =>
player.name.toLowerCase().includes(this.state.player.toLowerCase())).map(searchedPlayers => {
return(
<tr key={searchedPlayers.name}>
<td>{searchedPlayers.name}</td>
</tr>
);
})
}
.filter
。 - azium.filter
,但出现了错误。this.props.players.filter
,你根本不需要任何本地状态...你甚至不需要使用组件类,只需使用一个函数。 - azium