React JavaScript中的proc和method是什么?

8

我正在阅读这篇文章学习有关HOC的知识,但是我之前没有见过procmethod这两个术语。它们代表什么意思?

function refsHOC(WrappedComponent) {
  return class RefsHOC extends React.Component {
    proc(wrappedComponentInstance) {
      wrappedComponentInstance.method()
    }

    render() {
      const props = Object.assign({}, this.props, {ref: this.proc.bind(this)})
      return <WrappedComponent {...this.props}/>
    }
  }
}
2个回答

9

this.proc 指的是该方法

proc(wrappedComponentInstance) {
  wrappedComponentInstance.method()
}

wrappedComponentInstance.method()只是一个调用包装组件上任意方法的示例。文章说:

在下面的例子中,我们将探讨如何通过 refs 访问 WrappedComponent 的实例方法和实例本身。


所以,这两者都与 React 没有特别的关系。


proc是做什么的?它只返回对method()方法的引用吗?我以前从未听说过或读到过它。 - stackjlei
2
你想太多了。RefsHOC是一个类。该类定义了一个方法proc。类的实例可以通过this.proc访问该方法。这里有另一个简化的例子:class Foo { bar() {} baz() { this.bar() }。每个Foo的实例都将拥有barbaz方法。baz通过this.bar()调用bar。或者更简单地说:var foo = {bar() {}, baz() { this.bar() }}foo是一个具有两个方法的对象。foo.baz()也将通过this.bar()调用foo.bar - Felix Kling
2
“proc” 是做什么的?代码中有这样一行:wrappedComponentInstance.method()。它会调用传入参数的 method 方法。 - Felix Kling
1
抱歉,我完全以为这是一些奇怪的JavaScript本地操作,没有停下来想它是一个自定义方法。 - stackjlei
2
@stackjlei,你不是唯一一个这样搜索的人!我也是在寻找同样答案时发现了这个线程。从来没有想到它可能只是一个命名函数... - Keith Gaddis
我也曾经这么想过。 - Doug

4

我看到了这篇文章,一开始感到困惑。我将其转换为ES6语法,以便于那些同样感到困惑的用户更清楚地理解。

export default WrappedComponent =>
   class extends Component {

     //Proc function that gets called
     proc = wrappedComponentInstance => {
        wrappedComponentInstance.method()
     }

    render() {
        const props = { ...this.props, ...{ ref: this.proc } }
        return <WrappedComponent {...props} />
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接