首页 > 解决方案 > TypeError:无法读取未定义的属性“onSelect”

问题描述

我在反应中创建了一个类组件,并且需要在映射时在渲染函数中传递道具,但是我收到以下错误TypeError: Cannot read property 'onSelect' of undefined

下面是我的组件

class SelectLanguage extends Component {
    render() {
          let filterbrands = this.props.tvfilter.brand
          const filteredList = this.filterItems();

          if (filterbrands) {} else {}

          return (
              <div className="filter-options">
                  {filteredList &&
                      filteredList.map(item => (
                          <dl>
                              <dt className="mb-2">{item.title}</dt>
                              <input type="search" onChange={this.onSearchInputChange} className="search mb-2" placeholder="Search by Brand" />
                              {item.options.slice(0,this.state.itemsToShow).map(catname => (
                                  <dd
                                      key={catname.catgeory_name}
                                      className="mb-0"
                                  >
                                      <a href="#" onClick={props.onSelect.bind(null, item)}>{catname.catgeory_name}</a>
                                  </dd>
                              ))}
                          </dl>
                      ))}
                      <a className="btn btn-primary expandbutton" onClick={this.showMore}>{this.state.expanded ? (
                          <span>[ - less ]</span>
                          ) : (
                          <span>[ + more ]</span>
                          )
                      }</a>
              </div>
          );
      }
// PropTypes for SelectedLanguage
SelectLanguage.PropTypes = {
  selectedLanguage: PropTypes.string.isRequired,
  onSelect: PropTypes.func.isRequired
};
    }

问题出在这个锚上<a href="#" onClick={props.onSelect.bind(null, item)}>{catname.catgeory_name}</a>

注意:如果我使用函数而不是这样的类,它可以工作function SelectLanguage(props) {

标签: javascriptreactjsecmascript-6undefinedreact-props

解决方案


我相信您在将功能设置为之前缺少“this” <a href="#" onClick={this.props.onSelect.bind(null, item)}>


推荐阅读