我在es6 +中介紹自己,我很難嘗試將一個函數道具傳遞給另一個組件。如何在React.Component上正確傳遞另一個組件的功能道具?
這是我的代碼:
class ProductList extends React.Component {
constructor(props) {
super(props);
this.onVote = this.handleProductUpVote.bind(this);
}
handleProductUpVote(productId) {
console.log(productId +" was upvoted.")
}
render() {
const products = Data.map((product) => {
return (
<Product
key={'product-'+product.id}
id={product.id}
title={product.title}
description={product.description}
url={product.url}
votes={product.votes}
submitter_avatar_url={product.submitter_avatar_url}
product_image_url={product.product_image_url}
onVote={this.handleProductUpVote}
/>
);
});
return (
<div className="ui items">
{products}
</div>
);
}
}
我要傳遞的功能onVote在此組件(產品)
class Product extends React.Component {
handleUpVote() {
this.props.onVote(this.props.id).bind(this) /* the error is here, I am trying
to pass the id props, and invoke the onVote prop here */
}
render() {
return (
<div className="item">
<div className="image">
<img src={this.props.product_image_url} />
</div>
<div className="middle aligned content">
<div className="description">
<a onClick={this.handleUpVote}>
<i className="large caret up icon"/>
</a>
{this.props.votes}
</div>
<div className="description">
<a href={this.props.url}>
{this.props.title}
</a>
</div>
<div className="extra">
<span> Submitted by: </span>
<img
className="ui avatar image"
src={this.props.submitter_avatar_url}
/>
</div>
</div>
</div>
);
}
}
我在這裏等道具沒問題。我試圖調用handleUpVote函數,我用它綁定,但我不能讓它工作。幫幫我?
所以這就是我所做的,在 構造(道具){ \t \t超級(道具); \t \t this.onVote = this.handleProductUpVote.bind(this); \t}和產品組件onVote = {this.onVote},在此類產品組件上調用, handleUpVote(){ \t \t this.props.onVote(this.props.id); \t},我仍然有「Uncaught TypeError:無法讀取null屬性的'道具',從你的答案中,這是我的理解。你能詳細說明我該怎麼做嗎?我真的很感激 –
我已經用固定的產品組件更新了答案。你以錯誤的方式綁定handleUpVote,它應該在構造函數中完成。 –