我有一个名为MyDictionary的reactjs类,用于呈现python文件发送的数据。这个类返回一个字典结构。我只想通过一个单独的类从MyDictionary访问几个元素,通过一个单独的类从MyDictionary访问一个不同的元素集。我试过React.createElement(SomeOtherClass, {
,如下所示,但这不起作用.我遗漏了什么?
class MyDictionary extends React.Component {
render() {
return this.props.results.map((result, index) =>
React.createElement(
"div",
{ className: "col-sm-12" },
React.createElement(SomeOtherClass, {
key: result.id,
name: result.name,
index: result.index,
activity: this.props.index + 1,
images: this.props.image_labels
})
)
);
}
}
return MyDictionary;
发布于 2018-04-28 12:46:32
看起来,回调函数中的this
运算符与您所期望的不一样。
解决这一问题的最简单方法是在地图调用之前创建一个var到this
。
var _this = this;
然后在回调中使用_this
而不是this
。
您还应该阅读javascript闭包。
编辑: render()应该返回一个根元素.
class MyDictionary extends React.Component {
render() {
var _this = this;
var children = this.props.results.map((result, index) =>
React.createElement(
"div",
{ className: "col-sm-12" },
React.createElement(SomeOtherClass, {
key: result.id,
name: result.name,
index: result.index,
activity: _this.props.index + 1, // using _this
images: _this.props.image_labels // using _this
})
)
);
return React.createElement("div", null, children);
}
}
return MyDictionary;
https://stackoverflow.com/questions/50080848
复制