【发布时间】:2020-08-30 11:51:09
【问题描述】:
我正在尝试构建一个简单的 react 类,它在渲染时会根据从其父组件的 props 中接收到的图像路径返回标题和图像。
每次我尝试访问属性 this.props.eImage(本地图像路径)时,该属性的值都是未定义的,如 eImage:前两次渲染的未定义(组件由于未知原因渲染了 4 次)。我可以访问该房产,但由于某种原因无法访问它的价值。
这会导致渲染方法抛出错误“找不到模块‘未定义’。
我尝试使用 getDerivedState 和组件 willRecieveProps 等生命周期方法首先将图像路径存储在状态中,然后在渲染中使用它,但无济于事,两者的结果相同。
这很令人沮丧,因为这是一项简单的任务,但我无法让它工作。请帮忙。缩短的代码是:
家长:
import React, {Component} from 'react';
import Title from './Title/Title.js';
import Description from './Description/Description.js';
import OrderSection from './OrderSection/OrderSection.js';
import './excursionStyle.css';
const excursionList = [
{
excTitle : "Музейный Дрезден",
excDescription: `Дрезденская картинная галерея, как всегда, радует :)`}
]
class Excursion extends Component {
constructor(){
super();
this.state = {
};
};
getCurrentIndex = (name) => {
return excursionList.find(exc =>
exc.excTitle === name
)
}
componentDidMount() {
const currentExcursion = this.getCurrentIndex(this.props.match.params.name);
this.setState(currentExcursion);
};
render(){
return (
<div className="body">
<div className="excursion">
<Title eTitle={this.state.excTitle} eImage={this.state.excImageUrl}/>
<Description eDescription = {this.state.excDescription}/>
<OrderSection eTitle = {this.state.excTitle}/>
</div>
</div>
);
}
}
孩子:
import React, {Component} from 'react';
import './Title.css';
class Title extends Component{
constructor(props){
super(props);
}
render() {
console.log(this.props)
return (
<div>
<header className = "flex">
<p className = "f2 b">{this.props.eTitle}</p>
</header>
<div>
<img src={require(this.props.eImage)}></img>
</div>
</div>
);
}
}
export default Title;
【问题讨论】:
-
这些图片是否与您的文件夹相关?顺便说一句,你通过什么道具?
标签: javascript reactjs