简体   繁体   English

如何在React组件中的js和jsx中访问map函数之外的vairables

[英]how to access vairables outside of map function in js and jsx in a React component

var PieceList = React.createClass({

  render: function() {

    var pieces;
    if (this.props.pieces && this.props.onDeletePiece2) {
      var pieces = this.props.pieces.map(function (piece) {
        return (
          <Piece pieceData={piece} onDeletePiece3={this.props.onDeletePiece2} />
        )
      });
    }
    return (
      <div className="piecesTable">
        {pieces}
      </div>
    );  
  }
});

I'm stumped as to how to get this to work. 我很难过如何让它发挥作用。 The problem is that {this.props} is not available inside of the map function. 问题是{this.props}在map函数内部不可用。

Would a foreach be better here? 这里的foreach会更好吗? stumped, pls halp! 难倒,请停下来!

map is just a regular JavaScript method (see Array.prototype.map ). map只是一个常规的JavaScript方法(参见Array.prototype.map )。 It can take an argument that sets the context ( .map(callback[, thisArg]) ): 它可以采用一个设置上下文的参数( .map(callback[, thisArg]) ):

var PieceList = React.createClass({

  render: function() {

    var pieces;
    if (this.props.pieces && this.props.onDeletePiece2) {
      var pieces = this.props.pieces.map(function (piece) {
        return (
          <Piece pieceData={piece} onDeletePiece3={this.props.onDeletePiece2} />
        )
      }, this); // need to add the context
    }
    return (
      <div className="piecesTable">
        {pieces}
      </div>
    );  
  }
});

I would suggest going back and reading about this in JavaScript. 我建议回去和阅读this在JavaScript中。 When you pass an anonymous function to most methods (like .map , .forEach , etc.), it takes the global context (which is almost always window ). 当您将匿名函数传递给大多数方法(如.map.forEach等)时,它会占用全局上下文(几乎总是window )。 If you pass in this as the last argument, since that this is referring to the class you just created with React.createClass , it'll set the correct context. 如果你传入this作为最后一个参数,因为this是指你刚刚用React.createClass创建的类,它将设置正确的上下文。

In other words, the way you were trying to do it was access window.props , which obviously doesn't exist. 换句话说,你试图这样做的方法是访问window.props ,它显然不存在。 I'd if you opened your console to debug, you'd see the error Object Window doesn't have the property "props" or something very obfuscated. 如果你打开你的控制台进行调试,你会发现错误Object Window doesn't have the property "props"或者非常混淆的东西。

EDIT 2: React 0.14.x 编辑2:反应0.14.x

You can now define stateless functional components for components that do not require complex lifecycle event hooks or internal state 您现在可以为不需要复杂生命周期事件挂钩或内部状态的组件定义无状态功能组件

const PieceList = ({pieces, onDeletePiece2}) => {
  if (!onDeletePiece2) return;
  return (
    <div className="piecesTable">
      {pieces.map(x => (
        <Pieces pieceData={x} onDeletePiece3={onDeletePiece2}>
      ))}
    </div>
  );
};

EDIT 1: ES6 编辑1:ES6

As ES6 continues to become more prominent, you can also avoid nitpicky context issues by using an ES6 arrow function . 随着ES6继续变得更加突出,您还可以通过使用ES6 箭头功能来避免挑剔的上下文问题。

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>
    );
  }
}

To get this to run in most environments, you'd need to "transpile" it using something like babel.js 为了让它在大多数环境中运行,你需要使用像babel.js这样的东西来“转换”它


The quick answer is that you need to bind the proper this to the map callback by passing this as the second arg 简单的回答是,你需要绑定正确的thismap通过传递回调this为第二ARG

this.props.pieces.map(..., this);

This might be a better way to write your component tho 这可能是编写组件的更好方法

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>
    );
  }
});

Regarding your comment about map 关于你对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`

Will output 会输出

// "1"
// "2"

Notice how the second argument to map can set the context for the function. 注意map的第二个参数如何设置函数的上下文。 When you call this inside the function, it will be equal to the second variable that was sent to map . 当你调用this函数内部,这将是等于被送到第二个变量map

This is JavaScript basics and you should definitely read up more here 这是JavaScript基础知识,你一定要在这里阅读更多内容

Are you using a transpiler -- something like Babel? 您使用的是转换器吗 - 像Babel这样的东西? If so, this code will work fine: 如果是这样,这段代码将正常工作:

 if (this.props.pieces && this.props.onDeletePiece2) { var pieces = this.props.pieces.map((piece, i) => { return ( <Piece pieceData={piece} onDeletePiece3={this.props.onDeletePiece2} key={i}/> ) }); ... 

If you can't use a transpiler, you could do this: 如果您不能使用转换器,您可以这样做:

 if (this.props.pieces && this.props.onDeletePiece2) { var that = this; var pieces = that.props.pieces.map( function(piece, i) { return ( <Piece pieceData={piece} onDeletePiece3={that.props.onDeletePiece2} key={i}/> ) }) 

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 JSX 中访问 Map Function 之外的值 - Access value outside Map Function in JSX 如何将承诺函数映射到 JSX 组件? - How to map a promise function to a JSX component? 如何将 function 从 FUNCTIONAL 传递给 CLASS 组件并在渲染外部访问它(没有 prop ),在反应 js 中使用上下文? - How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js? 在React中,如何将JSX与返回更多JSX的JS函数一起返回? - In React, How to Return JSX together with JS Function that returns more JSX? 是否可以访问 React 组件外部的函数? - Is it possible to access a function outside a component in React? 在JSX中的嵌套映射函数内部反映JS打印数据 - React JS printing data inside a nested map function in JSX jsx中的功能图反应本机 - function map in jsx react native map function 未在反应 jsx 中呈现 - map function not rendering in react jsx JSX 不使用 React 返回 map function - JSX not returning map function with React 在 TypeScript 中使用 JS React 组件:JSX 元素类型“MyComponent”不是 JSX 元素的构造函数 - Using JS React component in TypeScript: JSX element type 'MyComponent' is not a constructor function for JSX elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM