无法使用 pubsub 组件将数据从 Product 组件传递到 Cartlist 组件。我需要将列表对象传递给 Cart 组件。产品组件呈现产品列表。因此,每个项目都必须作为props传递给 Cart 组件点击。
import React from 'react';
import PubSub from 'pubsub-js';
import Productlist from '../component/productlist';
import Addtocart from '../component/addtocart';
var createReactClass = require('create-react-class');
var Product = createReactClass({
addtocart:function(data){
console.log(data);
PubSub.publish('add-cart','helloworld')
},
render:function(){
var list = this.props.dataname;
return(
<div className="card hoverable">
<div className="card-image">
<img src={list.image} alt={list.name} className='shop-img' />
</div>
<div className="card-content">
<span className="card-title blue-text text-darken-2">{list.price} {list.currency}</span>
<p>{list.name}</p>
</div>
<Addtocart onClick={() => this.addtocart(list)} />
</div>
)
}
})
export default Product;
购物车列表组件
import React from 'react';
import PubSub from 'pubsub-js';
var createReactClass = require('create-react-class');
var Cartlist = createReactClass({
componentWillMount:function(data){
PubSub.subscribe('add-cart',function(data){
console.log(data);
});
},
// addtocart:function(data){
// console.log(data);
// },
render:function(){
var list = this.props.dataname;
return(
<div className="card hoverable">
</div>
)
}
})
export default Product;
演示问题的演示链接http://codesandbox.io/s/x7p856zmjp