【发布时间】:2020-02-25 04:52:02
【问题描述】:
我有一个组件,Tracks,它列出了歌曲和歌曲艺术家。艺术家名称是将视图带到 ArtistDetail 组件的链接。像这样:
我希望这样当用户点击艺术家姓名时,他们将被带到将显示“艺术家是 {name of artist clicked}”的艺术家详细信息组件。但正如您在上面的 sn-p 中看到的那样,艺术家姓名没有出现。当我在艺术家详细信息组件中进行一些安慰时,它说道具名称未定义
import React, { Component } from "react";
import SpotifyWebAPI from "spotify-web-api-js";
import { ArtistDetail } from "./ArtistDetail";
const spotifyApi = new SpotifyWebAPI();
export class Tracks extends Component {
constructor(props) {
super(props);
this.state = {
currentArtist: "lala"
};
}
openArtist = name => {
this.setState({
currentArtist: name
});
const artist = <ArtistDetail name={currentArtist}/>
//even with const artist = <ArtistDetail name="francis"/> it says undefined
this.props.switchView("ADetail");//this function is in change of changing the view from component to component.
return artist;// it does not seem to return the prop to the component
};
render() {
const { currentArtist } = this.state;
return (
<div>
<TableCell>
<Link
onClick={() => {
this.openArtist(artists.name);
}}
>
{console.log("the current artist")}
{console.log(currentArtist)}
{artists.name}
</Link>
</div>
</div>
);
}
}
export default Tracks;
这里是 ArtistDetail.js 组件
export const ArtistDetail = (props) => {
console.log("the prop name")
console.log(props.name);
return (
<div>
<h1> The artist is </h1>
<h1>{props.name}</h1>
</div>
)
}
我只是想在点击时将道具传递给组件。单击时,艺术家详细信息应获取艺术家的名称作为道具,然后 switchView 会将显示的组件从轨道切换到艺术家详细信息。 switchView 完成了它的工作。但是这个名字似乎并没有到达artistDetail。根据我的阅读,您似乎不能在渲染方法之外调用组件。但是如果没有 openArtist 方法,我不知道如何获得艺术家细节的道具
我尝试了这个内部轨道渲染方法:
{currentArtist != "lala" ? (<ArtistDetail name="francis"/>) && (this.props.switchView("ADetail"))
它仍然无法显示弗朗西斯
【问题讨论】:
标签: reactjs