ReactDOM.render无法读取属性

时间:2017-05-18 16:26:46

标签: reactjs react-bootstrap react-dom

Index.js:

import React from 'react'; 
import buttonsInstance from 'components/button-instance';
import {ReactDOM} from 'react-dom';

ReactDOM.render(buttonsInstance, document.getElementById('app'));

button-instance.js

import React from 'react';
import {ButtonToolbar} from 'react-bootstrap';
import {Button} from 'react-bootstrap';

const buttonsInstance = (
  <div>
    <ButtonToolbar>
      <Button bsStyle="primary" bsSize="large">Large button</Button>
      <Button bsSize="large">Large button</Button>
    </ButtonToolbar>
    <ButtonToolbar>
      <Button bsStyle="primary">Default button</Button>
      <Button>Default button</Button>
    </ButtonToolbar>
    <ButtonToolbar>
      <Button bsStyle="primary" bsSize="small">Small button</Button>
      <Button bsSize="small">Small button</Button>
    </ButtonToolbar>
    <ButtonToolbar>
      <Button bsStyle="primary" bsSize="xsmall">Extra small button</Button>
      <Button bsSize="xsmall">Extra small button</Button>
    </ButtonToolbar>
  </div>
);

我尝试使用https://react-bootstrap.github.io/components.html中的reactbootstrap

然后我收到了错误:

Uncaught TypeError: Cannot read property 'render' of undefined
    at Object.<anonymous> (index.js:9)
    at __webpack_require__ (bootstrap 571b93c…:657)
    at fn (bootstrap 571b93c…:85)
    at Object.<anonymous> (log-apply-result.js:30)
    at __webpack_require__ (bootstrap 571b93c…:657)
    at module.exports (bootstrap 571b93c…:706)
    at bootstrap 571b93c…:706

我使用webpackwebpack-dev-serveres6。我的reactreact-dom是最新的。我不知道如何解决这个问题。

3 个答案:

答案 0 :(得分:4)

像这样导入ReactDOM

import ReactDOM from 'react-dom';

它是一个默认导入(使用不同的方法导入完整的包)而不是import,这就是你得到错误的原因:

  

无法读取未定义

的属性'render'

或者您可以直接从render导入react-dom方法,如下所示:

import {render} from 'react-dom';

现在使用render直接呈现组件:

render(buttonsInstance, document.getElementById('app'));

答案 1 :(得分:1)

如果出现以下错误

Cannot read property xxx of undefined

如果您同时使用react-script-tsrollup,请使用import * as ...

import * as React from "react";
import * as ReactDOM from "react-dom";

答案 2 :(得分:0)

确保react版和react-dom版兼容。

例如对于react版本16.9.0,请使用'react-dom'版本16.9.0