【问题标题】:Using React Higher Order Component - Specifically react-sortable-hoc with redux使用 React 高阶组件 - 特别是 react-sortable-hoc 和 redux
【发布时间】:2016-09-09 23:04:53
【问题描述】:

我无法理解这个 HOC 的一个非常基本的部分,它对 NPM 有很好的吸引力,所以我猜这里有一个明显的答案,我错过了。

我有一个 TabListComponent,它从 redux 存储中呈现一个列表:

return this.props.tabs.map((tab) => {
    return (<li>{tab.title}</li>) 
})

在我的 MainComponent 类中,我正在导入 TabListComponent 和 react-sortable-hoc

import TabListComponent from './tabListComponent';
import { SortableContainer, SortableElement, arrayMove } from 'react-sortable-hoc';

我尽量不偏离文档太多,所以这就是我渲染组件的方式

const SortableItem = SortableElement(TabListComponent); //I wrap TabListComponent directly 

const SortableList = SortableContainer(() => {
    return (
        <ul className="tabs-inline-block">
            <SortableItem />
        </ul>
    );
});
onSortEnd () {
    console.log("I don't need a callback, but this gets called anyway. Is this necessary?");
}

render () {
    return (
        <div>
            <SortableList axis={'x'} onSortEnd={this.onSortEnd}/>
        </div>
    )
}

初始

拖动时

【问题讨论】:

  • 具体哪一部分你不明白?拖动时的CSS? onSortEnd() 回调?

标签: reactjs drag-and-drop higher-order-functions


【解决方案1】:

一个风格问题:你应该重构你的TabListComponent...

return this.props.tabs.map(({title}) => <li>{title}</li>)

更重要的是,您的 SortableList 对 React 无效。我认为重构它会有很大帮助。

const SortableItem = SortableElement(TabListComponent);

const SortableList = SortableContainer(({items}) =>
  <ul className="tabs-inline-block">
    {items.map((item, i) =>
      <SortableItem
        key={i}
        index={i}
        title={item.title}  // assumes `item` has a title property
      />
    )}
  </ul>
);

class SortableComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [{title: 'one'}, {title: 'two'}]
    };
  }

  onSortEnd({old, new}) {
    this.setState({
      items: arrayMove(this.state.items, old, new)
    });
  }

  render() {
    return (
      <SortableList
        items={this.state.items} // put your item models here
        onSortEnd={this.onSortEnd.bind(this)}
      />
    );
  }
}

您可能想了解更多关于 ES6 类的信息。使用对象文字查看它们在 ES5 中的类似物。如果您是 Javascript 或 ES6 的新手,React 教程有时可能难以理解。诸如...

method() {
  return 2 + 3;
}

...不能单独存在。它们必须包装在对象文字或类中。例如

const x = {
  method() {
    return 2 + 3;
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 2018-04-01
    • 2019-01-18
    • 2018-05-02
    • 1970-01-01
    • 2019-04-12
    • 2017-10-04
    • 2019-07-24
    相关资源
    最近更新 更多