首页 文章

反应onClick不触发功能

提问于
浏览
2

我有这个子组件生成列表元素,其中包含图像和标签内的2个图标 .

return <li><img src={bild[1]} alt="" /><span>{bild[2]}</span><a onClick={this.showBild} href="#"><i className="fa fa-eye"></i></a><a href="#"><i className="fa fa-trash-o"></i></a></li>

此返回是从父组件传递的prop的map函数的返回 .

某种程度上onClick事件不会触发我的showBild函数 .

我错过了什么 ?

继承我的整个反应代码,包括父组件和子组件(showBild类可以忽略)

<script type="text/jsx">
  var Bilder = React.createClass({
    getInitialState: function() {
      return {
        data:[
                ['1', 'http://localhost/foodoo/app/public/imgs/aichl.jpg', 'name.jpg'],
                ['2', 'http://localhost/foodoo/app/public/imgs/aichl.jpg', 'name.jpg'],
                ['3', 'http://localhost/foodoo/app/public/imgs/aichl.jpg', 'name.jpg'],
                ['4', 'http://localhost/foodoo/app/public/imgs/aichl.jpg', 'name.jpg'],
                ['5', 'http://localhost/foodoo/app/public/imgs/aichl.jpg', 'name.jpg']
            ],
        currentPic:[],
        display:'showBild clearfix dn'
      };
    },
    bild: function(){

    },
    render: function() {
      return (
        <div>
          <SingleBild data={this.state.data} chosenBild={this.bild} />
          <BildDetail data={this.state.currentPic} display={this.state.display} />
        </div>
      );
    }
  });

  var SingleBild = React.createClass({
    getInitialState: function() {
      return {
        bild:[]
      };
    },
    showBild: function(e){
      e.preventDefault();
      alert("yolo");
      this.props.chosenBild(this.state.bild);
    },
    render: function() {
      var displayBild = function(bild){
             return <li><img src={bild[1]} alt="" /><span>{bild[2]}</span><a onClick={this.showBild} href="#"><i className="fa fa-eye"></i></a><a href="#"><i className="fa fa-trash-o"></i></a></li>
      };
      return (
        <ul className="dashboardUl bilder clearfix">
          <h2>Gemeldete Bilder:</h2>
          {this.props.data.map(displayBild)}
        </ul>
      );
    }

  });

  var BildDetail  = React.createClass({

    render: function() {
      return (
        <div className={this.props.display}>
          <img src={this.props.data[1]} alt="" />
          <ul>
            <li><a href="#"><i className="fa fa-trash-o"></i></a></li>
            <li><a href="#"><i className="fa fa-ban"></i></a></li>
          </ul>
        </div>
      );
    }

  });


  React.render(<Bilder />, document.getElementById('bilder'));
</script>

1 回答

  • 2

    BildDetailrender 方法中,您应该引用 this 关键字或绑定它 . 例如:

    render: function() {
      var self = this;
      var displayBild = function(bild){
             return <li>...<a onClick={self.showBild} ....</a></li>
      };
      return (
        ....
      );
    }
    

    或者你可以绑定它:

    render: function() {
      var displayBild = function(bild){
             return <li>...<a onClick={this.showBild} ....</a></li>
      }.bind(this);
      return (
        ....
      );
    }
    

相关问题