下面是我使用(作爲道具被傳遞到組件)對象的基本佈局:陣營:調用地圖功能裏面的函數
bigObject {
overview: {
*not being used for current concern*
},
code: {
1: {
textArray: [*array of length 4 to 8*],
imgSrc: "string goes here"
},
2: {
textArray: [*array of length 4 to 8*],
imgSrc: "string goes here"
},
3: {
textArray: [*array of length 4 to 8*],
imgSrc: "string goes here"
},
}
}
我的構造函數:
constructor(props) {
super(props);
this.state = {
projectName: this.props.projectName,
info: bigObject[this.props.projectName]
}
this.renderInfo = this.renderInfo.bind(this);
this.renderText = this.renderText.bind(this);
console.log(this.state.info);
}
我想要做的是遍歷代碼對象,以便對於每個imgSrc,對象中的文本數組與迭代以創建列表元素沿照片邊。
renderInfo() {
return Object.keys(this.state.info.code).map(function(key, index) {
return (
<div className="code-snippet" id={name + key} key={key}>
<div className="code-description">
<ul>
{() => this.renderText(key)}
</ul>
</div>
<div className="code-img">
<img src={"/project-images/MongoScraper/" + placeholder[key].img} alt=""/>
</div>
</div>
)
});
}
每個IMG呈現正是我想要的,但renderText方法不是通過textArray迭代像我想:
renderText(key) {
console.log("hello world") //doesn't log
let placeholder = this.state.info.code;
return placeholder[key].text.map(function(keyValue, index) {
return (
<li>{placeholder[key].text[index]}</li>
)
});
}
渲染()方法:
render() {
return (
<div className="container code-descriptor-div">
{this.renderInfo()}
</div>
)
}
由於詞法範圍問題(「不能讀取未定義的屬性」結果不使用箭頭函數),因此我在調用renderText方法時使用了箭頭函數,但我知道該方法不是c完全一致,因爲控制檯沒有記錄「Hello world」。
當我在render()方法內部調用renderText方法時,它會正確地呈現列表元素,但這樣做並不適用於我構造其他組件的方式。
有沒有辦法像我想要的遍歷textArray?
這幫助了很多。謝謝。 –