显示数组元素ReactJS

时间:2016-11-17 13:19:25

标签: javascript reactjs syntax

UPD:如何在我的组件中显示数组的元素(WeatherCityName - h2)?可以看出数组已加载,但是当我指出属性时 - 发生错误,它可能是语法中的问题?

  var WeatherBox = React.createClass({
   handleWeatherSubmit: function(text) {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: 'cityName=' + text,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  render: function() {
    return (
      <div className="wetherBox">
      <h1> Weather</h1>
      <WeatherForm onWeatherSubmit={this.handleWeatherSubmit} />
      <WeatherCityName data={this.state.data[0]} />
      <WeatherList data={this.state.data} />
      </div>
      );
  }
});

var WeatherCityName = React.createClass({
    render: function(){
        return(
            <h2>{this.state.data[0].cityName}</h2>
            );
    }
});

Error

React

1 个答案:

答案 0 :(得分:0)

当然,只需将<h2>{weatherItem.cityName}</h2>直接放在<div>

var WeatherList = React.createClass({
  render: function() {
    var weatherNodes = this.props.data.map(function(weatherItem) {
      return (
        <div className="city-item-with-title">
          <h2>{weatherItem.cityName}</h2>
          <WeatherItem 
            cityid={weatherItem.cityid}
            type={weatherItem.type} 
            src={weatherItem.src} 
            temp={weatherItem.temp} 
            tempFrom={weatherItem.tempFrom} 
            tempTo={weatherItem.tempTo} 
            key={weatherItem.id}
          />
        </div>
      );
    });

    return (
      <div className="weatherList">
        {weatherNodes}
      </div>
    );
  }
});
  • 编辑:我不确定您希望将哪个天气项目用作标题,可能是this.props.data[0]
  • 编辑2:假设您想要使用第一个天气项目。
  • 编辑3:每个weatherItem的一个标题,在div中与相应的weatherItem一起分组。