【问题标题】:ReactJs Component not showingReactJs 组件未显示
【发布时间】:2017-12-21 08:05:49
【问题描述】:

我是 reactjs 的新手,正在尝试测试一个非常基本的组件,但是我所有的努力似乎都是徒劳的,因为它没有出现在浏览器中。

我正在使用 asp.net MVC 5 应用程序,我一直在关注本教程 https://reactjs.net/getting-started/tutorial_aspnet4.html,因为教程指出您需要添加具有一些依赖关系的 React.Web.Mvc4 Nuget 包。

我的简单 React 组件 (SimpleComponent.jsx)

var ComponentBox = React.createClass({
    render: function() {
        return (<div style="background-color:antiquewhite">Hello World ReactJs Component!</div>);
    }
});

ReactDOM.render(
    <ComponentBox />,
    document.getElementById('reactDiv')
);

我的剃刀观点很简单

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>


</head>
<body>
    <div id="reactDiv"></div>

    <script src="@Url.Content("~/Scripts/SimpleComponent.jsx")"></script>
</body>
</html>

我错过了什么吗?

【问题讨论】:

  • 控制台有错误吗?将style="background-color:antiquewhite" 更改为style={"background:antiquewhite"}
  • 控制台中的错误提示:style 属性需要从样式属性到值的映射,而不是字符串。例如,使用 JSX 时 style={{marginRight: spacing + 'em'}}。此 DOM 节点由 ComponentBox 渲染
  • 哦,只是我的错误:style={{"background:antiquewhite"}} 样式必须是一个对象。如果您对此进行了更改并且无法正常工作,请尝试在开始时添加 StyleComponent window.onload = function(){ 并关闭脚本 }
  • nope not working 语法错误
  • 这证明我是智障解决方案真的很简单,将样式属性更改为 style={{background:'antiquewhite'}} 使其工作

标签: asp.net-mvc reactjs reactjs.net


【解决方案1】:

我的问题的解决方案是替换我的 jsx 文件中的样式元素如下

var ComponentBox = React.createClass({
    render: function () {
        return (<div style={{background:'antiquewhite'}}>Hello World ReactJs Component!</div>);
    }
});

基于react docs“一般不推荐使用style属性作为元素样式的主要手段”

通过使用 javascript 对象将样式存储为属性,我希望这会对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2015-05-31
    • 2017-06-13
    • 2018-10-13
    • 2017-02-25
    • 2019-04-15
    • 2014-03-30
    相关资源
    最近更新 更多