在我的反应上看不到图像 - (代码)

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

我将jquery添加到我的index.html但我不知道为什么我看不到avatar_url和传入日期的名称

我检查 - 日期有效(在此删除登录名)

如何查看图片和名称?我做错了什么?

var Card = React.createClass({

  getInitialState: function(){
    return {};
  },

  componentDidMount: function(){

    // we need to define the callback info as component => to get the prop/state
    var component = this;

    // get data ( name ) from AJEX info => the return object is the arg 'data' 
    $.get("https://api.github.com/users/" + this.props.login, function(data){

      component.setState(data);    // set component as component of the callback data => in h3 we can get the data to show on ui 


    });
  },

  render: function(){
    return (
      <div>
        <img src={this.state.avatar_url} width="80"/>
        <h3>{this.state.name}</h3>
        <hr/>
      </div>
    );
  }
});




var Main = React.createClass({
  render: function(){
    return (
      <div>
        <Card login="myLogInName" />
      </div>
    )
  }
});

React.render(<Main />, document.getElementById("root"));
reactjs
2个回答
2
投票

看起来name属性是响应中的null。作为替代方案,我使用了login属性,因为它是一个值。

我还更新了代码以使用ES6语法,其中一个优点是箭头函数自动绑定this

class Card extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      avatar_url: null,
      login: null
    };
  }

  componentDidMount = () => {
    // get data ( name ) from AJAX info => the return object is the arg 'data' 
    $.get("https://api.github.com/users/" + this.props.login, data => {
      this.setState(data);
    });
  }

  render(){
    return (
      <div>
        <img src={this.state.avatar_url} width="80"/>
        <h3>{this.state.login}</h3>
        <hr/>
      </div>
    );
  }
};


class Main extends React.Component {
  render(){
    return (
      <div>
        <Card login="myLogInName" />
      </div>
    )
  }
};

ReactDOM.render(<Main />, document.getElementById("root"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

1
投票

在Reactjs的v.16更新之后,不推荐使用React.createClass创建组件。为了以这种方式创建反应组件,您需要使用create-react-class在文件顶部包含var createReactClass = require('create-react-class');

© www.soinside.com 2019 - 2024. All rights reserved.