React组件无法识别功能?

时间:2018-04-01 14:03:00

标签: reactjs laravel-mix

我在使用react.js时相当新。但我认为文档应该是可能的,对吧?错。

按照组件的文档结构,我正在尝试构建一个Filter组件。这是我的代码:

import React from "react";
import ReactDOM from "react-dom";

class FilterBar extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activeFilters: "",
      availableAttributes: []
    };
  }

  componentDidMount() {
    $.ajax("/activeFilters", {
      success: function(e) {
        this.setActiveFilter(e);
      },

      error: function(e) {
        alert(e);
      }
    });
  }

  componentWillUnmount() {}

  setActiveFilter(value) {
    this.setstate({
      activeFilters: value
    });
  }

  render() {
    return (
      <div id="auto_banner" className="inline_block col-sm-3 col-xs-12">
        <div id="toggle_filterBody" className="text-left col-xs-5 col-md-2">
          <span>
            <img src="img/filter2.png" />
          </span>
          <span>Toggle Filter</span>
        </div>

        <div id="Quick_Filter">
          <h3>Smart Filter</h3>
          <p>
            Begin searching through hundreds of vehicles quickly with this easy
            to use tool.
          </p>

          <hr />

          <form name="quick_filter" encType="application/x-www-form-urlencoded">
            <div id="year_range">
              <span className="tag">Year Range</span>

              <div>
                <input
                  className="col-xs-5 year_range"
                  type="text"
                  name="min-year"
                  value=""
                  placeholder="MIN: yyyy"
                />
                to
                <input
                  className="col-xs-5 year_range"
                  type="text"
                  name="max-year"
                  value=""
                  placeholder="MAX: yyyy"
                />
              </div>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

if (document.getElementById("InventoryDisplay")) {
  ReactDOM.render(document.getElementById("FilterBar"));
  ReactDOM.render("ok", document.getElementById("InventoryDisplay"));
}

现在当我刷新浏览器时,我收到一条错误,指出无法识别函数setActiveFilter。为什么呢?

3 个答案:

答案 0 :(得分:1)

问题是$ echo 'a' | awk -v x='.*' '$1 ~ x' a $ echo 'a' | awk -v x='' '$1 ~ x' a 将引用匿名函数而不是您创建的React对象:

this

如果您可以使用箭头功能,请尝试:

$.ajax('/activeFilters',{    
    success: function(e){

        this.setActiveFilter(e);
    },

    error:function(e){
        alert(e);
    }
});

答案 1 :(得分:1)

目前,您在全局范围内调用 setActiveFilter ,而不是在当前组件范围内。哟需要调用当前范围的函数,如:

  

this.setActiveFilter(E);

成功回调了ComponentDidMount

中写的ajax调用

答案 2 :(得分:1)

您必须在构造函数中绑定它

this.setActiveFilter = this.setActiveFilter.bind(this);

我很确定它会有所帮助;)