reactjs - 一次性传递整个 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 对象作为单个道具而不是单个道具传递给反应组件。我该怎么做?我没有得到值,还请解释为什么我也没有得到任何错误。
解决方案
您需要更改使用“评论”道具的方式。改变这个
const comment = props;
至
const { comment } = props
然后这将工作
<CompleteComment comment={comment1} />
推荐阅读
- javascript - 使用带有导航标签的 getElementsByTagName
- r - 将 lapply (或任何替代方法)与 data.table 一起使用以一次生成多个列
- python - Anaconda 总是安装 Python 3.7
- swift - 无法摆脱 UIviewcontroller 标头
- javascript - 遍历Javascript中的目录结构,每次点击都有回调
- python - 如何将计算列添加到熊猫列中的Dataframe计数频率
- python - 如何从 PyQt5 代码中继承实例的属性
- python - TensorFlow 编译运行很长时间
- sql - 有没有一种简单的方法来获取与 min 和 max 等聚合关联的 id?
- javascript - Javascript正则表达式按顺序替换数字