无法使用 React 和 Bootstrap 创建自定义样式

Posted

技术标签:

【中文标题】无法使用 React 和 Bootstrap 创建自定义样式【英文标题】:Cannot create custom style with React and 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。 【参考方案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 文件中?

以上是关于无法使用 React 和 Bootstrap 创建自定义样式的主要内容,如果未能解决你的问题,请参考以下文章

在使用 React-bootstrap 库时无法应用任何 Bootstrap 样式

React Bootstrap 工具提示无法在全屏上运行

使用 React Bootstrap 覆盖引导程序 4 时无法使 @media 查询工作

React Bootstrap 无法渲染

SO react-router-bootstrap 活动链接无法正常工作

无法在 React Bootstrap 的选项卡中使用表单