尝试传递 JSON 对象 REACTJS 不起作用

Trying to pass JSON object REACTJS not working

本文关键字:对象 REACTJS 不起作用 JSON      更新时间:2023-09-26

我开始参与 ReactJS,我正在尝试将一个 JSON 对象传递给我的标签,以便我可以在 UI 中显示它,但它一直说找不到元素。对此有任何帮助吗?或者为什么 props 对象没有 JSON 对象?提前致谢

var CommentBox = React.createClass({
  render: function() {
    return (
        <div className="img-container">
            <img src="{this.props.placementImage}" />
        </div>
    );
  }
});
var MP = [
    {
        id: "MP1001",
        placementImage: "https://www.aexp-static.com/intl/uk/rwd/images/UKHP_CM_promo_3.png",
        dts: "forever",
        dte: "forever",
        status: "",
        isDefault: false
    }
];
ReactDOM.render(
        <CommentBox mp={MP}/>,
        document.getElementById('content')
);

几件事:

  1. 您正在传递一个数组作为mp道具,但随后尝试像对象一样访问它。

  2. 您需要从 <img> src 属性中删除引号:

  3. 您需要访问实际的mp道具

作为参考,我从您的代码创建了一个 JSBin 示例来修复这些问题: http://jsbin.com/bohoqa/edit?html,js,output

var CommentBox = React.createClass({
  render: function() {
    return (
        <div className="img-container">
            <img src={this.props.mp.placementImage} />
        </div>
    );
  }
});
var MP = [
    {
        id: "MP1001",
        placementImage: "https://www.aexp-static.com/intl/uk/rwd/images/UKHP_CM_promo_3.png",
        dts: "forever",
        dte: "forever",
        status: "",
        isDefault: false
    }
];
ReactDOM.render(
        <CommentBox mp={MP[0]}/>,
        document.getElementById('content')
);

更改

<img src="{this.props.placementImage}" />

<img src={this.props.mp[index].placementImage} />

您必须将它们作为对象 {} 而不是 "{}" 传递

编辑:我没有注意到它是一个数组