【问题标题】:Using React Higher Order Component - Specifcally react-sortable-hoc使用 React 高阶组件 - 特别是 react-sortable-hoc
【发布时间】:2016-06-10 15:02:44
【问题描述】:

我无法理解这个 HOC 的一个非常基本的部分,它对 NPM 有很好的吸引力,所以我猜这里有一个简单的答案:

在他在NPM 上给出的示例中,我预先存在的组件在哪里。 {value} 是否应该替换为 <myComponent />?我知道这些包装器应该将我的组件(在本例中为组件)作为参数,但我认为我在这里遗漏了一些不可或缺的东西。任何帮助表示赞赏。他的示例文档如下

import React, {Component} from 'react';
import {render} from 'react-dom';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-list-hoc';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);

const SortableList = SortableContainer(({items}) => {
    return (
        <ul>
            {items.map((value, index) =>
                <SortableItem key={`item-${index}`} index={index} value={value} />
            )}
        </ul>
    );
});

class SortableComponent extends Component {
    state = {
        items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
    }
    onSortEnd = ({oldIndex, newIndex}) => {
        this.setState({
            items: arrayMove(this.state.items, oldIndex, newIndex)
        });
    };
    render() {
        return (
            <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />
        )
    }
}

render(<SortableComponent/>, document.getElementById('root'));

【问题讨论】:

  • 您是否尝试将
  • {value}
  • 替换为
  • 我的挂断与我在 SortableContainer() 上替换 {items} 有关现在我正在尝试这样做:
  • const SortableList = SortableContainer((CampaignLabels) => { return (
      {CampaignLabels.map((value, index) => item-${index}} index={index} value={value} /> )}
    ); });
  • 说我不能映射 CampaignLabels 是行不通的
  • 首先,你应该写({CampaignLabels}),而不是(CampaignLabels)。阅读destructuring。然后,CampaignLabels 必须作为 props 通过SortableList 传递。所以你应该有类似的东西:&lt;SortableList CampaignLabels=[]/&gt;。希望有所帮助:)
  • 标签: list reactjs drag-and-drop npm higher-order-functions


    【解决方案1】:

    SortableElement 将包装您的组件以从react-sortable-hoc 功能中受益。所以你必须写这样的东西(假设&lt;myComponent /&gt;是列表的一个元素):

    const SortableItem = SortableElement(myComponent);
    

    这将创建一个列表元素,该元素将呈现带有附加功能的myComponent

    ({value}) =&gt; &lt;li&gt;{value}&lt;/li&gt; 是一个代表 React 组件的无状态函数。你可以写:

    const myComponent = ({value}) => <li>{value}</li>;
    const SortableItem = SortableElement(myComponent);
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签