未定义classNames

时间:2018-07-05 18:04:38

标签: javascript reactjs

我是React开发的新手,并试图了解classNames如何在React中工作。

这是我书中的react代码。我刚刚复制了它。

const MOUNT = document.getElementById('root');
class App extends React.Component {
  render() {
    const klasses = classNames({
      box: true, // always apply the box class
      alert: this.props.isAlert, // if the prop is set
      severity: this.state.onHighAlert, // with state
      timed: false // never apply this class
    });
    return React.createElement(
      'div',
      {className: klasses},
      React.createElement('h1', {}, 'Hello world')
    );
  }
}
ReactDOM.render(React.createElement(App, {}), MOUNT);

我将包含此代码的脚本文件包含到html中,并且浏览器控制台显示了此类错误。

app.js:4 Uncaught ReferenceError: classNames is not defined
at App.render (app.js:4)
at finishClassComponent (react-dom.js:11320)
at updateClassComponent (react-dom.js:11297)
at beginWork (react-dom.js:11676)
at performUnitOfWork (react-dom.js:13644)
at workLoop (react-dom.js:13753)
at HTMLUnknownElement.callCallback (react-dom.js:1527)
at Object.invokeGuardedCallbackDev (react-dom.js:1566)
at invokeGuardedCallback (react-dom.js:1423)
at performWork (react-dom.js:13871)

出什么问题了?

4 个答案:

答案 0 :(得分:5)

classnames是您需要安装并导入到模块中的库。在您的shell中尝试npm i -S classnames,然后在JavaScript文件顶部尝试import classNames from 'classnames';

答案 1 :(得分:1)

因此,我想您将要安装类名npm模块来绑定对象中定义的条件类。

https://www.npmjs.com/package/classnames

npm i classnames --save

接下来,您需要在使用.js / .jsx文件之前要求它。

import classNames from 'classnames';

然后使用该模块将您的类绑定到React Element。

import classNames from 'classnames';
const MOUNT = document.getElementById('root');
class App extends React.Component {
  render() {
    const klasses = classNames({
        box: true, // always apply the box class
        alert: this.props.isAlert, // if the prop is set
        severity: this.state.onHighAlert, // with state
        timed: false // never apply this class
    });
    return React.createElement(
      'div',
      {className: klasses},
      React.createElement('h1', {}, 'Hello world')
    );
  }
}
ReactDOM.render(React.createElement(App, {}), MOUNT);

希望这会有所帮助,看起来Tholle首先到达那里。

答案 2 :(得分:1)

以上答案有效,但您需要更改将app.js文件导入index.html的行:

<script type="module" "src="app.js"></script>

以上建议对我有用(我正在读与您相同的React书)。

答案 3 :(得分:0)

  1. 根据@kust kust 的评论 您需要将 type="text/babel" 添加到 <script>app.js 标记中。
  2. 您需要将所有路径更新为相对路径...从 /./