如何在React内联CSS样式中添加!important

6
如何将 !important 添加到我的内联 CSS 属性中? 如果我在 2px 后添加它,整个样式都会被忽略。
import React from "react";

export default class Todo extends React.Component {
    render() {
        const {text} = this.props;

        const cardStyles = {
            borderWidth: '2px'
        };

        return (
            <div class="card mb-2 border" style={cardStyles}>
                <div class="card-body">
                    <h5 class="card-title m-0">{text}</h5>
                </div>
            </div>
        )
    }
}

尝试将cardStyles定义为类似于'border-width: 2px !important'的字符串,然后不要使用style={cardStyles},而是使用style="{cardStyles}" - Joint
1
请展示您如何包含它。展示渲染后的HTML可能也会有所帮助。这也值得一读 - Jon P
2个回答

13

3
内联样式比!important具有更高的优先级,因此从技术上讲,您不需要使用!important - Anh Pham
4
不,我使用了Bootstrap的样式,并且它们覆盖了我的内联样式。 - Baterka
我还没有能够让这个解决方案正常工作。https://codesandbox.io/s/1rrpxryjx4 - Dan Cron
1
^ 因为它的 style.setProperty,而不是 setProperty。@DanCron - ncubica
谢谢,@ncubica。将我的元素.setProperty的错字改为element.style.setProperty就可以了。 - Dan Cron

1

非常容易实现... 4年前...开始思考,React不是2018年最好的框架学习。 - Baterka
1
是的,我同意这似乎是一个巨大的疏忽。我知道避免使用 !important 是最佳实践,但有很多情况下确实需要使用它。 - Ollie F
@Baterka,你没有做错选择,React是领先的框架,只是你正在尝试实现一个边缘案例。我已经使用React将近3年了,这是我第一次看到这个特定的需求。 - ncubica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接