【发布时间】:2020-04-20 06:05:19
【问题描述】:
我正在尝试使用 React 创建一个最终将接收 JSON 数据的表(通过 HTTP 请求)。我目前将数据存储在我的第一个组件的状态中,然后在我的第二个组件中呈现表格。
我希望表格中的每一行都包含一张专辑封面的图片,然后是有关曲目、艺术家和专辑标题的文本数据。对于这篇文章,我将包含我的一行数据,以便您可以看到它是如何存储在 state 中的。
我目前无法渲染存储为状态字符串的图像。为了使它工作,我可以对我的 getRowsData() 函数进行哪些更改?或者,也许我需要更改调用图像字符串的方式?任何帮助或建议将不胜感激。
状态(图像字符串为 .jpeg 文件)可在此处找到:
import React, { Component, useState, Fragment } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import AudioPlayer from './AudioPlayer';
import Table from './Table/TrackInfo';
import '../components/AudioPlayer.css';
import '../adrian_trinkhaus.jpeg';
export default class PostContent extends Component {
constructor(props) {
super(props);
this.state = {
tracklist: this.props.tracklist,
data: [
{
'Album Art': '../adrian_trinkhaus.jpeg',
'Artist': 'The Olivia Tremor Control',
'Track Title': 'The Opera House',
'Album Title': 'Music From The Unrealized Film Script: Dusk At Cubist Castle'},
]
}
}
render() {
console.log(this.props.tracklist)
return (
<Fragment>
{/*Audio Player and Related*/}
<AudioPlayer />
<Link id='home-link' to='/' activeClassName='active'>Homepage</Link>
<div className="word-content">
<h2 className="show-title">{this.props.showTitle}</h2>
<div className="episode-post-content">{this.props.content}</div>
<Table data={this.state.data} />
<div className="bottom-link">
<Link id='home-link' to='/' activeClassName='active'>Homepage</Link>
</div>
</div>
</Fragment>
)
}
}
表是在这里创建的:
import React, { Component } from 'react';
export default class Table extends React.Component {
constructor(props) {
super(props);
this.getHeader = this.getHeader.bind(this);
this.getRowsData = this.getRowsData.bind(this);
this.getKeys = this.getKeys.bind(this);
}
getKeys = function () {
return Object.keys(this.props.data[0]);
}
getHeader = function () {
var keys = this.getKeys();
return keys.map((key, index) => {
return <th key={key}>{key.toUpperCase()}</th>
})
}
getRowsData = function () {
var items = this.props.data;
var keys = this.getKeys();
return items.map((row, index) => {
return <tr key={index}><RenderRow key={index} data={row} keys={keys} /></tr>
})
}
render() {
return (
<div>
<table>
<thead>
<tr>{this.getHeader()}</tr>
</thead>
<tbody>
{this.getRowsData()}
</tbody>
</table>
</div>
);
}
}
const RenderRow = (props) => {
return props.keys.map((key, index) => {
return <td key={props.data[key]}>{props.data[key]}</td>
})
}
【问题讨论】: