React 将数据从另一个组件传递到有状态组件

React Passing Data to Stateful Component from Another Component

我正在尝试学习 React 并正在创建一个简单的下拉菜单,它显示了一个供用户选择的排序选项列表。单击任何一种排序都会对当前 HTMl Ul 进行排序(按字母顺序、最旧-最新等...)

我有一个名为 SortSelection 的组件,其中包含下拉菜单和更新 ul 所需的所有逻辑。它是这样调用的(在另一个组件中):

      <div className="collectionsSortDropdownContainer">
        <SortSelection
          options={[
            { value: '-publishDate', name: 'Newest' },
            { value: '+publishDate', name: 'Oldest' },
          ]}
          handleSort={this.handleSort.bind(this)}
        />
      </div>

里面SortSelection.jsx,我目前是这样写的:

const SortSelection = ({
  options, extraClass, handleSort,
}) => {
   //...necessary logic

但是,我意识到我应该将 SortSelection 更新为有状态组件,因为我将做一些额外的 UI 事情,比如显示 Sort 的当前值并在用户上添加一个蓝色复选标记-已选择排序。

我无法弄清楚如何重写我的组件,使其看起来像这样:

class SortSelection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentSort: currentSort
    };
  }
}

同时还要确保传递三个必要的数据参数(options、extraClass、handleSort)以实例化组件。我怎样才能正确地做到这一点?

我假设您正在尝试在 SortSelection

中使用某些状态

你绝对不需要为此使用 class 组件,功能组件也可以,因为我们有 React State Hook

因此,为了使它对您来说不那么复杂,只需像您已经使用的那样继续使用功能组件:

像这样使用useState:

const { useState } = require("react")

const SortSelection = ({
  options, extraClass, handleSort,
}) => {
  const [currentSort, setCurrentSort] = useState();  //<-- useState hook
   //...necessary logic
   return (
     //...JSX
   )
}

currentSort 现在是一个状态,每次您想更改该状态并触发重新渲染时,请使用 setCurrentSort