通过道具传递的功能未定义

时间:2018-07-07 12:49:50

标签: javascript reactjs

我有三个组成部分:TopicscreenListviewListrow。我正在传递函数renderrow和我定义的其他两个属性 TopicscreenListview

现在,当我在func中调用Listview时,道具将按照Listrow函数中的定义传递给renderrow,但是onRowclick函数正在当我在Listrow中检查时,传递给undefined的是Listrow

如何解决此错误并将onRowclick作为函数传递给Listrow

Topicscreen.js

class Topicscreen extends Component {
  constructor() {
    super();
    this.onRowClick = this.onRowClick.bind(this);
  }

  componentDidMount() {
    this.props.dispatch(topicaction.Fetchtopics());
  }

  renderLoading() {
    return <p>Loading...</p>;
  }

  renderrow(rowid, topic) {
    //const selected = this.props.checkselection[rowid]
    const selected = "";
    return (
      <Listrow selected={selected} clicking={this.onRowClick} rowid={rowid}>
        <h3>{topic.title}</h3>
        <p>{topic.description}</p>
      </Listrow>
    );
  }

  onRowClick(rowid) {
    this.props.dispatch(topicaction.selectedchoice(rowid));
  }

  render() {
    if (!this.props.topicsByurl) return this.renderLoading();
    return (
      <div className="TopicsScreen">
        Hi I am topic screen
        <h1>Choose any three of the below topics</h1>
        <Listview
          rowid={this.props.topicsurlArray}
          row={this.props.topicsByurl}
          func={this.renderrow}
        />
      </div>
    );
  }
}

Listview.js

import React, { Component } from "react";
import _ from "lodash";

export default class Listview extends Component {
  constructor() {
    super();

    this.show = this.show.bind(this);
  }

  show(rowid) {
    return this.props.func(rowid, _.get(this.props.row, rowid));
  }

  render() {
    console.log("props in listview", this.props);
    return (
      <div>
        <ul>{_.map(this.props.rowid, this.show)}</ul>
      </div>
    );
  }
}

Listrow.js

import React, { Component } from "react";

export default class Listrow extends Component {
  clicking() {
    this.props.clicking(this.props.rowid);
  }

  render() {
    console.log("list row called");
    console.log("listrow props", this.props);
    const background = this.props.selected ? "#c0f0ff" : "#fff";
    return (
      <div style={{ background }} onClick={this.clicking.bind(this)}>
        {this.props.children}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

您还需要将renderrow方法绑定到Topicscreen构造函数中,否则this.onRowClick内的renderrow不会是您期望的。

class Topicscreen extends Component {
  constructor(props) {
    super(props);
    this.onRowClick = this.onRowClick.bind(this);
    this.renderrow = this.renderrow.bind(this);
  }

  // ...
}