为什么我无法从 ReactDOM.render() 回调中获取对我的组件的引用?

Why can I not get a reference to my component from the ReactDOM.render() callback?

我有以下代码:

const priceCalculator = ReactDOM.render(<PriceCalculator />, reactHolder);

我稍后需要在我的代码中使用 priceCalculator,但 ESLint 抱怨我不应该使用 ReactDOM.render() 的 return 值。就在那时我发现你可以 pass a 3rd argumentReactDOM.render() 这是一个回调。太棒了我想...

ReactDOM.render(<PriceCalculator />, reactHolder, function(priceCalculator) {
    // do something with priceCalculator
});

priceCalculator 未定义。在调试器中,我暂停异常并发现 this 设置为我的 React Component 当我在这个函数中时。所以我重写了它...

ReactDOM.render(<PriceCalculator />, reactHolder, function() {
    const priceCalculator = this;
    // do something with priceCalculator
});

仍未定义。怎么回事?

我正在使用 Webpack 编译 es6 React 代码(使用 babel)。

ESLint docs page you linked it says to use a callback ref中:

ReactDOM.render() currently returns a reference to the root ReactComponent instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root ReactComponent instance, the preferred solution is to attach a callback ref to the root element.

Source: React Top-Level API documentation

因此,您可以通过 prop 将回调传递给根组件,并通过根节点的 ref prop 在组件的 render 方法中引用组件的根节点来调用它。

例如(working fiddle):

class Hello extends React.Component {
  render () {
    return (
      <div ref={(node) => this.props.cb(node)}>
        Hello {this.state.name}
      </div>
    )
  }
}

let node

ReactDOM.render(<Hello cb={(n) => node = n} />, ...);

console.log(node)

注意:这种方法很幼稚,因为 ReactDOM.render 可能并不总是同步呈现,在这种情况下 console.log 语句将打印 "undefined"。 (参见上面的引用:“React 的未来版本在某些情况下可能会异步渲染组件”。)