【问题标题】:Why does the class attribute disappear from "h1" element rendered by React?为什么类属性会从 React 渲染的“h1”元素中消失?
【发布时间】:2016-08-30 18:34:39
【问题描述】:

这是我的 React.Component 的 render 方法:

class Layout extends React.Component {
    constructor() {
        super();
        this.state = {name: "Brian"};
    }

    changeName(name) {
        this.setState({name});
    }

    render() {
        return (
            <h1 class="row">hello</h1>
        );
    }
}

ReactDOM.render(
  <Layout/>,
  document.getElementById('app')
);

这里是渲染的 HTML:

<div id="app" class="container">
    <h1 data-reactroot="">hello</h1>
</div>

我不明白,为什么h1 的class 属性消失了?

【问题讨论】:

  • 在React 你必须使用className 而不是class

标签: javascript html reactjs jsx


【解决方案1】:

React 元素没有class 属性。您必须使用className 属性。

这里提供了原因,在 React 的文档中:
https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components

【讨论】:

  • 类是javascript中的保留字
【解决方案2】:

您需要使用className 而不是class

<h1 className="row">hello</h1>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2021-10-05
    • 2017-08-11
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多