针对每个表行

时间:2018-05-15 10:36:57

标签: javascript reactjs function bind

我有一些数据可以通过.map()打印出来 喜欢这个代码

tabRow(){
         // CSS style for font Icon 
        const editIcon = {
          color: 'blue',
          fontSize: '1.3em',
          padding: '0 5px',
        };
        const trashIcon = {
          color: 'red',
          fontSize: '1.3em',
          padding: '0 5px',
        };
       if(this.state.products instanceof Array){
         return this.state.products.map(function(object, i){
             return(
                    <tr key={ i }>
                        <td>{ object.id }</td>
                        <td>{ object.title }</td>
                        <td>{ object.body }</td>
                        <td width="200px">
                      <Icon name="edit" onClick={() => this.handleClick(i)} style={editIcon}
                       className="editIconClass" />
                      <Icon name="trash" style={trashIcon} className="trashIconClass" />
                    </td>
                    </tr>
                  )

         })
       }
     }

我在表格中使用tabRow()

<tbody>
   {this.tabRow()}
</tbody>

我也可以简单地登录handleClick()并在构造函数this.handleClick = this.handleClick.bind(this);中绑定此代码我可以看到我的视图,但是当我点击运行函数时出现此错误:

Uncaught TypeError: Cannot read property 'handleClick' of undefined
    at onClick (app.js:61529)
    at HTMLUnknownElement.callCallback (app.js:40524)
    at Object.invokeGuardedCallbackDev (app.js:40562)
    at Object.invokeGuardedCallback (app.js:40611)
    at Object.invokeGuardedCallbackAndCatchFirstError (app.js:40625)
    at executeDispatch (app.js:40890)
    at executeDispatchesInOrder (app.js:40912)
    at executeDispatchesAndRelease (app.js:41010)
    at executeDispatchesAndReleaseTopLevel (app.js:41021)
    at forEachAccumulated (app.js:40991)

我该怎么做才能解决它?

And my App.js file looks like this
require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';


import Master from './components/Master';
import CreateProduct from './components/CreateProduct';
import DisplayProduct from './components/DisplayProduct';
import UpdateProduct from './components/UpdateProduct';


render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateProduct} />
        <Route path="/display-item" component={DisplayProduct} />
        <Route path="/edit/:id" component={UpdateProduct} />
      </Route>
    </Router>,
        document.getElementById('root'));

和我的把手点击

handleClick(i){
        console.log('Click happened', i);
      }

1 个答案:

答案 0 :(得分:3)

您无法直接在地图功能中访问此功能,您应该将其绑定。您可以通过多种方式完成此操作。例如,您可以使用箭头功能。这应该是您案例的代码:

.ignore

您还可以添加return this.state.products.map((object, i) => ( <tr key={ i }> ... </tr> )) 作为地图函数as described here的第二个参数。