Reactjs 在这个例子中,思考需要绑定吗?
在React的教程中,在创建ProductTable组件时,表最初是静态创建的,如下所示:Reactjs 在这个例子中,思考需要绑定吗?,reactjs,Reactjs,在React的教程中,在创建ProductTable组件时,表最初是静态创建的,如下所示: var ProductTable = React.createClass({ render: function() { var rows = []; var lastCategory = null; this.props.products.forEach(function(product) { if (product.category !== lastCategor
var ProductTable = React.createClass({
render: function() {
var rows = [];
var lastCategory = null;
this.props.products.forEach(function(product) {
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
// return table
var ProductTable=React.createClass({
render:function(){
var行=[];
var lastCategory=null;
this.props.products.forEach(函数(产品){
if(product.category!==lastCategory){
rows.push();
}
rows.push();
lastCategory=product.category;
});
//返回表
但是,在本例后面的部分中,表是这样创建的:
var ProductTable = React.createClass({
render: function() {
var rows = [];
var lastCategory = null;
this.props.products.forEach(function(product) {
if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
return;
}
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
}.bind(this)); // <-- this is the question
// return table
var ProductTable=React.createClass({
render:function(){
var行=[];
var lastCategory=null;
this.props.products.forEach(函数(产品){
if(product.name.indexOf(this.props.filterText)==-1 | |(!product.stocked&&this.props.inStockOnly)){
返回;
}
if(product.category!==lastCategory){
rows.push();
}
rows.push();
lastCategory=product.category;
}.bind(this));//这是因为.forEach()
将有自己的上下文。因此,如果在forEach()中使用this
,可能会出现意外错误
这就是为什么您应该将.bind()
与组件的上下文绑定forEach()
,以便在forEach()中使用它的上下文
下面的例子应该说明这一点
a=[1,2,3,4]
b={
a:函数(){
console.log(这个)
},
b:函数(){
a、 forEach(函数(){
console.log(这个)
})
},
c:函数(){
a、 forEach(函数(){
console.log(这个)
}).绑定(此)
}
}
b、 ()
b、 b()
b、 c()
这是因为.forEach()
将有自己的上下文。因此,如果在forEach()
中使用此,您可能会遇到意外错误
这就是为什么您应该将.bind()
与组件的上下文绑定forEach()
,以便在forEach()中使用它的上下文
下面的例子应该说明这一点
a=[1,2,3,4]
b={
a:函数(){
console.log(这个)
},
b:函数(){
a、 forEach(函数(){
console.log(这个)
})
},
c:函数(){
a、 forEach(函数(){
console.log(这个)
}).绑定(此)
}
}
b、 ()
b、 b()
b、 c()
在第一个示例中,没有使用this。
而在第二个示例中,使用了this.props.inStockOnly
。我假设您知道为什么绑定(this)
是必需的,因为它将绑定到类。在第一个示例中,没有使用this。
而在第二个示例中,使用了this.props.inStockOnly
。我假设您知道绑定(this)的原因
是必需的,因为它将绑定到类。或者,您可以将this
作为第二个参数传递给forEach
,以实现相同的效果,而无需创建另一个函数,这就是bind
所做的。它应该是.forEach(Function(){…},this)谢谢,罗斯!这太棒了。我很感激。或者,你可以将这个作为第二个参数传递给forEach
,以在不创建另一个函数的情况下实现相同的效果,这就是绑定所做的。它应该是forEach(Function(){…},This)谢谢,罗斯!这太棒了。我很感激。