【问题标题】:How can I add a class attribute to my html element through ReactJS?如何通过 ReactJS 向我的 html 元素添加类属性?
【发布时间】:2020-11-12 12:41:16
【问题描述】:

我希望 Reactjs 在我的 html 中的 div 中添加一个名为“hello”的类。

我知道我可以简单地在 JavaScript 中通过编写 element.classList.add("hello");

但是 React 显示关键字“.add”的错误

我该怎么做?

【问题讨论】:

  • 您的问题表明您是 React 的新手,并且没有掌握使用 React、Vue 等 MVC 类库与创建和手动更新之间的根本区别元素。我建议通过一些 React 教程来了解更多关于这种差异的信息。
  • 非常感谢@T.J.Crowder 的建议,是的,我是新来的反应,所以当我遇到这个问题时,我试图将我的原生 JavaScript 项目转换为反应。但是再次感谢,我非常感谢您的回答,我一定会按照您的建议了解更多的反应。
  • 这能回答你的问题吗? React Js conditionally applying class attributes...有时我觉得我是唯一一个在寻找答案的人...

标签: javascript html reactjs react-native


【解决方案1】:

您可以通过在渲染组件时包含该类来做到这一点。举个例子,如果你在做一个函数式组件,它会像这样返回:

return (
    <div>
        This is the content of the div
    </div>
);

您可以将其更改为:

return (
    <div className={someCondition ? "hello" : ""}>
        This is the content of the div
    </div>
);

...其中someCondition 控制div 是否应具有hello 类。

这是一个示例,当您单击 div 时添加类,再次单击时将其删除,等等:

const {useState, Component} = React;

function FunctionalExample() {
    const [hasClass, setHasClass] = useState(false);
    const onClick = e => setHasClass(v => !v);
    return (
        <div
            className={hasClass ? "hello" : ""}
            onClick={onClick}
        >
            Example in a functional component
        </div>
    );
}

class ClassExample extends Component {
    constructor(props) {
        super(props);
        this.state = {
            hasClass: false
        };
        this.onClick = this.onClick.bind(this);
    }
    onClick() {
        this.setState(({hasClass}) => ({hasClass: !hasClass}));
    }
    render() {
        const {hasClass} = this.state;
        return (
            <div
                className={hasClass ? "hello" : ""}
                onClick={this.onClick}
            >
                Example in a class component
            </div>
        );
    }
}

ReactDOM.render(
    <div>
        <FunctionalExample />
        <ClassExample />
    </div>,
    document.getElementById("root")
);
.hello {
    color: blue;
    font-style: italic;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

【讨论】:

  • 或者只是className={name}所以直接设置类?
  • @JuleWolf - 如果name 是一个变量,是的,或者className="hello" 是一个文字值。但是 OP 的问题是关于 adding 一个类,所以我认为它最初不存在,然后由于某些条件变为真而被添加。
猜你喜欢
  • 2011-12-26
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2017-02-26
  • 2019-06-29
相关资源
最近更新 更多