如何在 React 的类名字段中传递带参数的函数?

How to pass function with argument in classname field in React?

我的 React 项目中有以下组件。我想要做的是向 <li> 元素添加一个 className 属性。将其设置为等于 getSortByClass() 方法的 return 值,并将 sortByOptionValue 作为参数传入。

import React from 'react';
import './SearchBar.css';

const sortByOptions = {
  'Best Match': 'best_match',
  'Highest Rated': 'rating',
  'Most Reviewed': 'review_count'
}
function getSortByClass(sortByOption){
  if (this.state.sortBy === sortByOption) {
    return 'active';
  }
  else {
    return '';
  }
}
function handleSortByChange(sortByOption){
  this.setState({
     sortBy: sortByOption
   });
}
export class SearchBar extends React.Component{
    renderSortByOptions(){
      return Object.keys(sortByOptions).map(sortByOption => {
        let sortByOptionValue = sortByOptions[sortByOption];
        return <li className={getSortByClass(sortByOptionValue)} key={sortByOptionValue}> {sortByOption} </li>;
      });
    }

    constructor(props) {
        super(props);
        this.state = {
          term: '',
          location: '',
          sortBy: 'best_match',
        };
    }
    render(){
      return (
      <div className="SearchBar">
        <div className="SearchBar-sort-options">
          <ul>
            {this.renderSortByOptions()}
          </ul>
        </div>
        <div className="SearchBar-fields">
          <input placeholder="Search Businesses" />
          <input placeholder="Where?" />
        </div>
        <div className="SearchBar-submit">
          <a>Lets Go</a>
        </div>
        </div>
      );
    }
  }

  export default SearchBar;

设置类名字段后出现错误:TypeError: Cannot read property 'state' of undefined

....
function getSortByClass(sortBy, sortByOption){
  if (sortBy === sortByOption) {
    return 'active';
  }
  else {
    return '';
  }
}

export class SearchBar extends React.Component{
    handleSortByChange = (sortByOption) => this.setState({ sortBy: sortByOption});

    renderSortByOptions(){
      const that = this;

      return Object.keys(sortByOptions).map(sortByOption => {
        let sortByOptionValue = sortByOptions[sortByOption];
        return <li className={getSortByClass(that.state.sortBy, sortByOptionValue)} key={sortByOptionValue}> {sortByOption} </li>;
      });
    }
    ....

将您的状态传递给 getSortByClass 方法,因为它无法访问 this,因为它写在 class 之外。还要在 class 中写入 handleSortByChange,因为它正在从 this.

访问 setState

也可以把代码美化为:

renderSortByOptions(){
          const that = this;

          return Object.keys(sortByOptions).map(sortByOption => {
            let sortByOptionValue = sortByOptions[sortByOption];
            return (
               <li className={that.state.sortBy === sortOption ? 'active' : ''} 
                   key={sortByOptionValue}
               > 
                   {sortByOption} 
               </li>
           );
        });
     }