我有三个组成部分:Topicscreen
,Listview
,Listrow
。我正在传递函数renderrow
和我定义的其他两个属性
Topicscreen
至Listview
。
现在,当我在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>
);
}
}
答案 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);
}
// ...
}