【问题标题】:JS - React what does it mean this notation [duplicate]JS - 反应这个符号是什么意思[重复]
【发布时间】:2020-10-21 16:03:54
【问题描述】:

您好,我对此表示法有疑问:

export default DropTarget('answerSlot', spec, collect)(ItemSlot);

只需要知道在 dropTarget() 之后是另一个 (className) 时要搜索什么或它意味着什么

我的完整代码如下所示:

import React from "react";
import {DropTarget} from "react-dnd";

interface IProps {
    children ?: any,
    connectDropTarget: (item: any) => any,
}

interface IStates {

}

const spec = {
    drop(props, monitor, component) {
        const item = monitor.getItem()
        console.log(monitor.getDropResult());
        props.onDrop(item);
        return item;
    },
};

const collect = (connect, monitor) => {
    return {
        connectDropTarget: connect.dropTarget(),
    };
};

class ItemSlot extends React.PureComponent<IProps, IStates> {


    render() {
        const { connectDropTarget } = this.props;
        return (
            connectDropTarget(
                <div style={{width: '200px', height: '50px', backgroundColor: 'blue'}} className={'m-1'}>
                {this.props.children}
            </div>,
            )
        );
    }
}

export default DropTarget('answerSlot', spec, collect)(ItemSlot);

【问题讨论】:

  • 不知道细节但看起来DropTarget是一个你用3个参数调用的函数,它的返回类型是另一个接受一个类作为参数的函数,然后你用@987654327调用它@ 返回在原始 ItemSlot 之上具有额外内容的类或函数组件。
  • 这能回答你的问题吗? Understanding React Higher-Order Components
  • DropTarget 函数返回另一个函数。这与currying的概念有关。它可能是一个Higher-Order Component,它基本上包装了您的 ItemSlot 组件并以某种方式对其进行了增强。

标签: javascript reactjs


【解决方案1】:

这是一个高阶函数,这里解释得很好https://medium.com/javascript-scene/higher-order-functions-composing-software-5365cf2cbe99

TL;DR;它基本上是一个返回另一个函数的函数。 使用一些信息预初始化函数很有用,这些信息随后包含在高阶函数的范围内。在 React 中还有高阶函数的概念,称为高阶组件,您可以在其中组合组件并使用某些特定功能对它们进行预初始化

想象一下

const HelloWorld = ({ lang }) => <div>Hello world {lang}</div>

const withLang = lang
      => Component 
      => props 
      => <Component {...props} lang={lang} />

// here we enhance the HelloWorld component with a default lang of EN
// now HelloWorldEn will always output Hello world en
const HelloWorldEn = withLang(en)(HelloWorld)

高阶函数的好处是您可以将它们与其他组件重用。

下面是另一个我觉得很好解释的用例

const languageFilter = lang => predicate => predicate.language === lang

const list = [{ name: "test", language: "en"}, {name: "foo", language: "de"}] 

list.filter(languageFilter("en"))

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2012-11-03
    • 2016-10-10
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2014-01-19
    相关资源
    最近更新 更多