编辑 2:反应 0.14.x
您现在可以为不需要复杂生命周期事件挂钩或内部状态的组件定义 stateless functional components
const PieceList = ({pieces, onDeletePiece2}) => {
if (!onDeletePiece2) return;
return (
<div className="piecesTable">
{pieces.map(x => (
<Pieces pieceData={x} onDeletePiece3={onDeletePiece2}>
))}
</div>
);
};
编辑 1:ES6
随着 ES6 越来越突出,您还可以通过使用 ES6 arrow function 来避免挑剔的上下文问题。
class PieceList extends React.Component {
renderPiece(piece) {
return <Piece pieceData={piece} onDeletePiece3={this.props.onDeletePiece2} />;
}
render() {
if (!this.props.onDeletePiece2) return;
return (
<div className="piecesTable">
{this.props.pieces.map(piece => this.renderPiece(piece))}
<div>
);
}
}
要让它在大多数环境中运行,您需要使用 babel.js 之类的东西“转译”它
快速回答是,您需要通过将this 作为第二个参数传递来将正确的this 绑定到map 回调
this.props.pieces.map(..., this);
这可能是编写组件的更好方法
var PieceList = React.createClass({
renderPiece: function(piece) {
return <Piece pieceData={piece} onDeletePiece3={this.props.onDeletePiece2} />;
},
render: function() {
if (!this.props.onDeletePiece2) return;
return (
<div className="piecesTable">
{this.props.pieces.map(this.renderPiece, this)}
</div>
);
}
});
关于您对map的评论
var x = {a: 1, b: 2};
['a', 'b'].map(function(key) {
// `this` is set to `x`
// `key` will be `'a'` for the first iteration
// `key` will be `'b'` for the second iteration
console.log(this[key]);
}, x); // notice we're passing `x` as the second argument to `map`
会输出
// "1"
// "2"
注意map 的第二个参数如何设置函数的上下文。当您在函数内调用this 时,它将等于发送到map 的第二个变量。
这是 JavaScript 基础知识,您绝对应该阅读更多 here