我的函数存在问题,该函数将数据从数组转换为不同组件中的列表。我认为问题在于我不了解在哪里放置document.GetElementById().
会出现错误document.getElementById(...) is null
。是因为我尝试在渲染之前访问特定位置吗?那我应该如何访问它,也许它与组件生命周期有关?这是我的代码:
import React, { Component } from 'react';
import Day from "./day";
import image1 from "./img/eggs.jpg";
class Stuff extends Component {
constructor(props){
super(props);
this.makeList = this.makeList.bind(this);
}
makeList(array) {
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
render() {
const source = {
breakfast: [
{
id: 1,
name: "eggs",
img: image1,
description: "Start a day with delicious and nutricious eggs!",
ingridients: ['2 eggs', 'two slices of toast', 'bacon', 'butter']
},
...
]}
return (
<div>
<Day {...source}
makeList={this.makeList} />
</div>
);
}
}
export default Stuff;
和 Day 组件,React 发生错误:
import React, { Component } from 'react';
import "./day.css";
class Day extends Component {
render() {
const appChild = document.getElementById('foo').appendChild(this.props.makeList(this.props.source.breakfast.ingridients));
return (
<div className="displayOne">
<img src= {this.props.breakfast[0].img} alt="eggs" />
<h3>{this.props.breakfast[0].description}</h3>
<div id="foo">
<p>{appChild}</p>
</div>
</div>
);
}
}
export default Day;
感谢您的帮助和理解!
慕斯709654
相关分类