我是react新手。我正在尝试创建一个名为 StationBrowserForHome (TSX) 的组件。在 render() 函数中,我想渲染一个如下所示的 DOM 元素:
<div class = "big-group">
<div class = "small-group>
<div class="item"></item>
<div class="item"></item>
...
<div class="item"></item>
</div>
<div class = "small-group>
<div class="item"></item>
<div class="item"></item>
...
<div class="item"></item>
</div>
...
</div>
所以我尝试在 componentWillMount() 中创建该 DOM 树,将其设置为状态变量“divItems”,然后在 render() 中检索它
export class StationBrowserForHome extends Component <{}, any> {
componentWillMount (){
var divItems = document.createElement("div");
var divSeven = document.createElement("div");
for (var i = 0; i < 7; i++) {
var singleItem = document.createElement('<div className="station-item"><div className="row"><StationBrowserItemInfo/></div><div className="row station-name">Station {i}</div></div>');
divSeven.appendChild(singleItem);
console.log("singleItem: "+singleItem);
console.log("divSeven: "+divSeven);
}
divItems.appendChild(divSeven);
this.setState({divItems:divItems});
}
render() {
return (
<div className="container-fluid text-center browser">
<div className="cover-div">
<ArrowButton/>
<div className="text-center list-station" id="station-browser">
{ this.state.divItems }
</div>
</div>
</div>
);
}
}
我收到了这条错误信息:
VM19339 invariant.js:42 Uncaught Error: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead
如有任何帮助,我们将不胜感激!
最佳答案
React 很棒,因为您可以将事物分解为可重用的组件。这段代码有点违背了 React 的全部含义。
例如,componentWillMount 中的所有内容都应该位于带有 Prop numberOfItems
的组件内,然后基于此您将呈现在我看来是站台项目的内容。
export class StationList extends React.Component<{stations: IStation[]}, {}> {
render() {
return (
<div className='stations'>
{this.getStationItems}
</div>
);
}
private getStationItems() {
const itemsDiv = this.props.stations.map((station, index) => {
return (
<div className='station'>
//........
// other stuff here
</div>
)
});
return itemsDiv;
}
}
然后回到 StationBrowserForHome
组件,我们只是:
const stations: IStation[] = [
{
id: 'station1',
purpose: 'purpose1'
},
{
id: 'station2',
purpose: 'purpose2'
}
];
return (
<div className="container-fluid text-center browser">
<div className="cover-div">
<ArrowButton/>
<div className="text-center list-station" id="station-browser">
<StationList stations={stations} />
</div>
</div>
</div>
);
上面的代码只是一个通用模板,不在 IDE 前面,但这是基本要点。
关于reactjs - 如何将 javascript 生成的 DOM 元素传递给渲染函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525599/