首页 > 解决方案 > 一次性传递整个 json 类对象以将组件作为道具而不是单个道具进行反应

问题描述

index.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

const comment1 = {
    "text":"Nice job",
    "author_name":"Aru",
    "avatarUrl": 'http://www.gravatar.com/avatar/3b3be63a4c2a439b013787725dfce802?d=identicon'    
}



function CompleteComment(props){
    const comment = props;
    return (
    <div className="UserInfo">      
          <img className="Avatar"
            src={comment.avatarUrl}
            alt={comment.author_name}
          />
          <div className="UserInfo-name">
            {comment.author_name}
          </div>
          <div className="comment">
             Comment: {comment.text}
          </div>
    </div>
    
    );
}
  
function App(){
    return (
        <div>
            <!-- working,but only comment text is passed not all props -->
            <CompleteComment text={comment1.text} />

            <!-- Not Working -->
            <CompleteComment comment={comment1}  />        </div>
    )
}
  

ReactDOM.render(
      <App />,
      document.getElementById('root')
);

在上面的代码中,我试图将整个 comment1 JSON 对象作为单个道具而不是单个道具传递给反应组件。我该怎么做?我没有得到值,还请解释为什么我也没有得到任何错误。

标签: reactjsreact-propsreact-component

解决方案


您需要更改使用“评论”道具的方式。改变这个

const comment = props;

const { comment } = props

然后这将工作

<CompleteComment comment={comment1}  />

推荐阅读