javascript - 在 react 中将函数作为 Prop 传递,无法读取未定义的属性 '_handleEvent'

标签 javascript reactjs create-react-app

我尝试在 React 中实现一个类表。一个表有多行,每行都有一个按钮。首先,我尝试传递一个函数 handleEvent。

现在,我总是以: 类型错误:无法读取未定义的属性“_doDeleteItem”

存在某种绑定(bind)错误,但我无法弄清楚。

干杯

class Table extends Component {
  constructor(props,context) {
    super(props,context);
    this.state = { k : 3 };
    this._handleEvent = this._handleEvent.bind(this);
  }

  _handleEvent (e) {
     console.log('delete')
   }

   render() {
      var rows = [];
      var lastCategory = null;
      this.props.results.slice(-this.state.k).forEach(function(r) {
      rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
      });
      return(
        <Panel>
         <ListGroup fill>
          {rows}
         </ListGroup>
        </Panel>
      );
     } 
    }
    export default Table;

   class Rows extends Component{
     render() {
      return(
        <ListGroupItem>
          <b>Text:</b><Button onClick = {this.props.deleteItem} type="False"><b>True</b></Button><br/>
        </ListGroupItem>
      );
      }
     }

最佳答案

this 不是 forEach 中的组件实例.要么使用箭头函数,绑定(bind)匿名函数,要么将 this 作为第二个参数传递给 forEach:

 this.props.results.slice(-this.state.k).forEach(function(r) {
   rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
 }.bind(this));

 this.props.results.slice(-this.state.k).forEach(function(r) {
   rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
 }, this);

关于javascript - 在 react 中将函数作为 Prop 传递,无法读取未定义的属性 '_handleEvent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45275951/

相关文章:

php - 无法使用 jQuery 正确访问复杂的 json 对象

javascript - React Router 4 失败的上下文类型

reactjs - 无法使用 docker 容器运行 react 应用程序

webpack - antd 自定义原色

reactjs - 如何在创建React应用程序中使用scss变量?

javascript - 创建图像模态

javascript - pouchdb不在Linux上用electron和leveldb创建本地数据库

javascript - 在哪里可以找到 firebase 身份验证 API 的所有错误代码和消息的列表

html - 基于认证安全问题的条件渲染

javascript - 导入模块时 'as'是什么意思?