2016-10-28 26 views
2

我正在使用react-bootstrap NPM程序包來使我的React組件正常顯示。我需要自定義其中的一部分,因此我遵循official React-Bootstrap documentation,但代碼會引發錯誤index.jsx:5 Uncaught TypeError: Cannot read property 'addStyle' of undefined無法使用React和Bootstrap創建自定義樣式

這是我的自定義Button組件代碼:

import React from "react"; 
import Button from 'react-bootstrap/lib/Button'; 
import bootstrapUtils from 'react-bootstrap/lib/utils/bootstrapUtils'; 

bootstrapUtils.addStyle(Button, 'custom'); 

export default class MediaItemButton extends React.Component { 
    render() { 

     return (
      <div> 
       <style type="text/css">{` 
       .btn-custom { 
        background-color: purple; 
        color: white; 
       } 
       `}</style> 
       <Button bsStyle="primary">Custom</Button> 
      </div> 
     ); 
    } 
} 
+0

您bootstrapUtils對象不存在,請確保您有正確的路徑反應的自舉包時,你的WebPack包裝該或者其他的東西 ?如果是這樣,你需要做額外的步驟,使其在組件類聲明中可用 –

+0

我已檢查路徑,並且bootstrapUtils文件在那裏。它在導出中也有addStyle函數。另外,我正在使用Webpack。 – JustLogin

回答

5

改成這樣:

import { bootstrapUtils } from 'react-bootstrap/lib/utils'; 
4

你可以做到這一點還有:

import React from "react"; 
    import Button from 'react-bootstrap/lib/Button'; 
    import bootstrapUtils from 'react-bootstrap/lib/utils/bootstrapUtils'; 

    bootstrapUtils.addStyle(Button, 'custom'); 

    export default class MediaItemButton extends React.Component { 
     render() { 
      var styles={ 
       "backgroundColor" : "purple", 
       "color"   : "white" 
      }; 
      return (
       <div> 
        <Button style={styles} bsStyle="primary">Custom</Button> 
       </div> 
      ); 
     } 
    } 
+0

我可以在.css中存儲我的樣式,還是我必須在JS中聲明它們? – JustLogin

+0

@JustLogin兩者都可以....通過普通CSS或作爲樣式對象 – Poiz

+0

上述代碼如何重構以將樣式存儲在.css文件中? – JustLogin

0

bootstrapUtils是一個叫出口,而不是默認的,因此你需要使用{}周圍。

嘗試使用: import { bootstrapUtils } from 'react-bootstrap/lib/utils/bootstrapUtils';

+0

同樣的錯誤。 – JustLogin

+0

Geraint幾乎是正確的。您必須從路徑中刪除「/ bootstrapUtils」。看到我的答案 –

相關問題