![](/img/trans.png)
[英]React Native: How to access a variable from parent component in child component?
[英]How to access parent variable from child
我正在嘗試從B訪問A中的變量(在下面的示例中)。 我沒有從A擴展B,因為A只是一個容器。
function A() {
var Parent = this;
this.container = [];
}
A.prototype.add = function(Item) {
Parent.container.push(Item);
}
function B() {
}
B.prototype.exec = function() {
console.log(Parent.container[0]) //Uncaught ReferenceError: Parent is not defined
}
var Manager = new A();
var Item = new B();
Manager.add(B);
Item.exec();
如何從Item
訪問Parent
?
function A() {
this.container = [];
}
A.prototype.add = function(Item) {
this.container.push(Item);
}
function B(Parent) {
this.Parent = Parent;
}
B.prototype.exec = function() {
console.log(this.Parent.container[0]) //Uncaught ReferenceError: Parent is not defined
}
var Manager = new A();
var Item = new B(Manager);
A.add(B);
B.exec();
function A() {
this.container = [];
}
A.prototype.add = function(Item) {
//assigning parent property only if Item is added
Item.Parent = this;
this.container.push(Item);
}
function B() {
this.Parent = null;
}
B.prototype.exec = function() {
console.log(this.Parent.container[0])
}
var Manager = new A();
var Item = new B();
Manager.add(Item);
Item.exec();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.