【问题标题】:Cannot create custom style with React and Bootstrap无法使用 React 和 Bootstrap 创建自定义样式
【发布时间】:2017-03-11 07:05:04
【问题描述】:

我正在使用react-bootstrap NPM 包来使我的React 组件看起来正确。我需要自定义其中一些,所以我关注official React-Bootstrap documentation,但是代码抛出了错误index.jsx:5 Uncaught TypeError: Cannot read property 'addStyle' of undefined

这是我自定义的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>
        );
    }
}

【问题讨论】:

  • 你的 bootstrapUtils 对象不存在,确保你有正确的 react-bootstrap 包路径,你是用 webpack 还是其他东西打包它?如果是这样,您需要执行额外的步骤以使其在组件类声明中可用
  • 我已经检查了路径,并且 bootstrapUtils 文件在那里。它还在导出中具有 addStyle 功能。另外,我正在使用 Webpack。

标签: javascript css twitter-bootstrap reactjs react-bootstrap


【解决方案1】:

改成这样:

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

【讨论】:

    【解决方案2】:

    bootstrapUtils 是一个命名导出而不是默认导出,因此您需要在它周围使用{}

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

    【讨论】:

    • Geraint 几乎是对的。您必须从路径中删除“/bootstrapUtils”。看我的回答
    【解决方案3】:

    你也可以这样做:

        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>
                );
            }
        }
    

    【讨论】:

    • 我可以将我的样式存储在 .css 中,还是必须在 JS 中声明它们?
    • 如何重构上面的代码以将样式存储在 .css 文件中?
    猜你喜欢
    • 2023-03-18
    • 2020-07-23
    • 2017-12-22
    • 2022-07-14
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2021-12-31
    • 2021-07-19
    相关资源
    最近更新 更多