React 元素的方法在 map() 函数内部绑定时显示奇怪的行为
React element's method shows weird behaviour when bound inside map() function
我在学习 ReactJS 的初期,在使用 Array.prototype.map() 方法渲染多个元素时遇到了非常令人费解(而且烦人!)的问题。我已经在网上搜索了解决方案,并查看了几本书但没有成功。这是我要实现的代码:
var ExampleComponent = React.createClass({
handleClick: function(event) {
event.preventDefault();
console.log("Click is working");
},
getInitialState: function() {
return {
exampleArray: ["one", "two", "three"]
};
},
render: function() {
return (
<div>
{this.state.exampleArray.map(function(item, index) {
return (
<button className={item} key={index} onClick={this.handleClick}>{item}</button>
);
})}
</div>
);
}
});
按钮渲染得很好。我希望在单击它们中的任何一个时,指定的字符串将记录在控制台中。相反,单击按钮会导致页面重新加载...感觉我在这里明显遗漏了一些关于 React 工作原理的东西。
以前有人遇到过这个问题吗?这里的罪魁祸首是什么?有没有更好的方法来实现相同的模式?
任何有关问题的意见都将不胜感激!
您需要使用父上下文调用 map()
:
// Call map with context.
{this.state.exampleArray.map(function(item, index) {
return (
<button className={item} key={index} onClick={this.handleClick}>
{item}
</button>
);
}, this)}
// Call map with implicit context via arrow function.
{this.state.exampleArray.map((item, index) => {
return (
<button className={item} key={index} onClick={this.handleClick}>
{item}
</button>
);
})}
我在学习 ReactJS 的初期,在使用 Array.prototype.map() 方法渲染多个元素时遇到了非常令人费解(而且烦人!)的问题。我已经在网上搜索了解决方案,并查看了几本书但没有成功。这是我要实现的代码:
var ExampleComponent = React.createClass({
handleClick: function(event) {
event.preventDefault();
console.log("Click is working");
},
getInitialState: function() {
return {
exampleArray: ["one", "two", "three"]
};
},
render: function() {
return (
<div>
{this.state.exampleArray.map(function(item, index) {
return (
<button className={item} key={index} onClick={this.handleClick}>{item}</button>
);
})}
</div>
);
}
});
按钮渲染得很好。我希望在单击它们中的任何一个时,指定的字符串将记录在控制台中。相反,单击按钮会导致页面重新加载...感觉我在这里明显遗漏了一些关于 React 工作原理的东西。
以前有人遇到过这个问题吗?这里的罪魁祸首是什么?有没有更好的方法来实现相同的模式?
任何有关问题的意见都将不胜感激!
您需要使用父上下文调用 map()
:
// Call map with context.
{this.state.exampleArray.map(function(item, index) {
return (
<button className={item} key={index} onClick={this.handleClick}>
{item}
</button>
);
}, this)}
// Call map with implicit context via arrow function.
{this.state.exampleArray.map((item, index) => {
return (
<button className={item} key={index} onClick={this.handleClick}>
{item}
</button>
);
})}