我希望我的父母将一些条件传递给孩子,以筛选列表并从列表中返回符合条件的企业。 例如。
if (service === pub && town === Ipswich)
return business.name.
到目前为止,这是我的父组件:
import React, { Component } from 'react';
import logo from './backgroundimage.jpg';
import './App.css';
import {Child} from './Child.js';
class Parent extends Component {
state={
service: '',
town: ''
}
search (service,town) {
this.setState({service, town});
}
render() {
return (
<div className="App">
<Child service={this.state.service} town={this.state.town}/>
</div>
);
}
}
export default Parent;
理想情况下,我希望输入是从两个下拉框中的多个选项中进行选择。
到目前为止,这是我的子组件,我想保留该列表,并将过滤后的项目返回以在父组件中呈现。
import React from 'react';
import {Parent} from './App.js';
export class Child extends React.Component{
constructor(props){
super(props)
}
state={
businesses: [
{ service:'Pub',
town:'rosewood',
name:'Rising Sun'},
{ service:'Club',
town:'ipswich',
name:'Metro'},
{ service:'Club',
town:'ipswich',
name:'Switch'},
{ service:'Restaurant'
town:'ipswich',
name: 'Dustys'},
{ service:'Pub',
town:'rosewood',
name: 'The Royal Hotel'},
]
};
check () {
const {service,town} = this.props;
return list.find(item => {
if (service === item.service){return item.name}
if (town === item.postCode){return item.name}
})
}
render () {
return (
<div>
<p>{this.check()}</p>
</div>
);
}
}
我希望将列表存储在子组件中,以便在构建列表时可以不断扩展列表,同时使其与父组件分离。
答案 0 :(得分:1)
尝试使用Array.filter()
,然后映射到结果数组上:
render(){
const {service, town} = this.props
return(
<div>
state.businesses.filter(
o => o.service === service && o.town === town // filter the array based on some conditions
).map(
item => <p>{item.name}</p> // print the name of the filtered items
)
</div>
);
}