我如何将我的JSON从SearchBar传递到ApartmentByCity并从那里显示所需的数据。如何在ReactJs中做到这一点?

问题描述 投票:0回答:1

如何将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;



reactjs react-component
1个回答
0
投票
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>
    )
© www.soinside.com 2019 - 2024. All rights reserved.