如何将JSON从SearchBar传递到ApartmentByCity并从中显示所需的数据。此SearchBar组件位于App组件中。我如何在ReactJs中做到这一点?我刚刚开始学习ReactJs。我会很感激的。预先感谢。
SearchBar.js
class SearchBar extends Component {
constructor (props) {
super(props)
this.state = { city: '',
apartment:[],
};
}
handleSearch (e) {
this.setState({ city: e.target.value })
}
handleGoClick () {
fetch(`/apartment/city/${this.state.city}`)
.then(response => response.json())
.then(data=> this.setState({
apartment: data
}))
};
render ()
{
return (
<div>
<form onSubmit={e => e.preventDefault()}>
<input
type='text'
size='45'
placeholder='Barcelona'
onChange={this.handleSearch.bind(this)}
value={this.state.city} />
<button
type='search'
onClick={this.handleGoClick.bind(this)}>
<b> Search </b>
</button>
</form>
</div>
)
}
}
export default SearchBar
The below code is in the ApartmentByCity.js
import React from 'react';
const ApartmentByCity = (apartment) => {
return(
<div>
<h1> Apartments List </h1>
<h5>Title: {apartment.title}</h5>
<h5>Price: {apartment.price} </h5>
})}
</div>
)
};
export default ApartmentByCity;
const ApartmentByCity = (props) => {
let {apartment} = props;
return(
<div>
<h1> Apartments List </h1>
<h5>Title: {apartment.title}</h5>
<h5>Price: {apartment.price} </h5>
})}
</div>
)
};
export default ApartmentByCity;
并且在searchbar.js文件中:
import ApartmentByCity from './apartment.js';
以及在搜索栏的呈现中:
// this.state.apartments = [{title: 'hello', price: 123}]
let apartment = this.state.apartments[0];
let aptProps = {apartment}
return (
<div>
{this.state.apartments.map((apartment, key) => {
return (
<ApartmentByCity key={`apt-${key}`} apartment={apartment} />
);
})
}
<ApartmentByCity apartment={apartment} />
<ApartmentByCity {...aptProps} />
</div>
)