首页 > 解决方案 > Javascript中连续出现许多粗箭头?

问题描述

我在我正在考虑的 NPM 库的文档中遇到了这段代码。

有人试图向我解释至少第一行在做什么?看起来这 3=>位意味着这些函数都返回函数。

我认为自己(也许是错误的)擅长 javascript。thisis 放在一起的方式似乎过于复杂,至少对我来说很明显。我想如果我足够努力的话,如果我能多一点,但关于这件事的感觉过于混乱,所以我搬到了另一个图书馆。

第一行和分配顺序,函数开始和停止的地方对我来说是最少的。

const withTimer = timerProps => WrappedComponent => wrappedComponentProps => (
  <Timer {...timerProps}>
    {timerRenderProps =>
      <WrappedComponent {...wrappedComponentProps} timer={timerRenderProps} />}
  </Timer>
);

class TimerWrapper extends React.Component {
    shouldComponentUpdate() {
        return false;
    }

    render() {
        return (
            <div>
                <div>Simple text</div>
                <Timer.Consumer>
                    {() => this.props.timer.getTime()}
                </Timer.Consumer>
            </div>
        );
    }
}

const TimerHOC = withTimer({
    initialTime: 5000,
})(TimerWrapper);

<TimerHOC />

标签: ecmascript-6jsx

解决方案


本质上是这样

function withTimer(timerProps) {
    function withWrappedComponent(WrappedComponent) {
        function withWrappedComponentProps(wrappedComponentProps) {
            return (
                <Timer {...timerProps}>
                    {(timerRenderProps) => (
                        <WrappedComponent {...wrappedComponentProps} timer={timerRenderProps} />
                    )}
                </Timer>
            );
        }
        return withWrappedComponentProps;
    }
    return withWrappedComponent;
}

如果这有帮助

或者作为两种形式之间的一种中介,就像这样

function withTimer(timerProps) {
    return function (WrappedComponent) {
        return function (wrappedComponentProps) {
            return (
                <Timer {...timerProps}>
                    {(timerRenderProps) => (
                        <WrappedComponent {...wrappedComponentProps} timer={timerRenderProps} />
                    )}
                </Timer>
            );
        };
    };
}

推荐阅读