【问题标题】:React Passing Data to Stateful Component from Another ComponentReact 从另一个组件向有状态组件传递数据
【发布时间】:2021-11-06 15:00:07
【问题描述】:

我正在尝试学习 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 工作,例如显示排序的当前值并在用户选择的排序上添加一个蓝色复选标记。

我无法弄清楚如何将我的组件重写为如下所示:

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

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

【问题讨论】:

    标签: javascript html reactjs components


    【解决方案1】:

    我假设您正在尝试使用 SortSelection 中的某些状态

    您绝对不需要为此使用类组件,函数式组件也可以,因为我们有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

    【讨论】:

      猜你喜欢
      • 2021-01-02
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2020-03-12
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      相关资源
      最近更新 更多