【发布时间】:2017-03-12 18:45:27
【问题描述】:
基础组件
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { addToCart, removeFromCart, changeQuantity } from '../../actions/CartActions';
@connect(null, { addToCart, removeFromCart, changeQuantity })
class Product extends Component {
constructor() {
super();
this.addToCart = this.addToCart.bind(this);
}
addToCart() {
this.props.addToCart(this.props.product);
}
removeFromCart() {
this.props.removeFromCart(this.props.product);
}
changeProductQuantity() {
this.props.changeQuantity(this.props.product);
}
render() {
return (
<div className="product_box">
<h3>{this.props.product.title}</h3>
<Link to={`details/${this.props.product._id}`}>
<img src={this.props.product.image_url} alt={this.props.product.title} />
</Link>
<p>{this.props.product.description}</p>
<p className="product_price">{this.props.product.price} {this.props.product.currency}</p>
<Link onClick={this.addToCart} className="addtocart" />
<Link to={`details/${this.props.product._id}`} className="detail" />
</div>
);
}
}
Product.propTypes = {
product: PropTypes.shape({
_id: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
image_url: PropTypes.string,
price: PropTypes.string,
currency: PropTypes.string,
}),
addToCart: PropTypes.func,
removeFromCart: PropTypes.func,
changeQuantity: PropTypes.func,
};
export default Product;
子组件
import React from 'react';
import Product from '../common/Product';
class InlineProduct extends Product {
render() {
const { product } = this.props;
return (
<tr>
<td>
<img src={product.image_url} alt={product.title} />
</td>
<td>{product.title}</td>
<td className="align-center">
<input className="quantity-input" type="text" value="1" onChange={this.changeProductQuantity} />
</td>
<td className="align-right">{product.price} {product.currency}</td>
<td className="align-right">{product.price} {product.currency}</td>
<td className="align-center">
<a onChange={this.removeFromCart}>
<img src="images/remove_x.gif" alt="remove" /><br />Remove
</a>
</td>
</tr>
);
}
}
export default InlineProduct;
看起来第二个组件不能从第一个组件继承方法。 我可以从子组件调用父级的方法。有任何想法吗? 我认为 props 验证是可以的,因为它是静态的,但需要一些解决方案来使方法可以从子组件访问。
【问题讨论】:
-
“我可以从子组件中调用父级的方法。” 那是正常的。你的意思是“不能”?
-
我很难找到链接,但我记得他们在 React 文档中的某处说,基本上,“在 Facebook 的数千个组件中,我们从未遇到过继承有意义的案例作文。”
-
谢谢你的想法
-
所以基本上 FB 想把多年积累的 CS 知识扔到窗外,只是因为他们没有发现需要它。 (是的,我知道他们创建了 React。)但是,我认为大多数人没有使用 React 来构建像 FB 这样的东西,所以他们不可能说你不应该使用继承。看看这两种方法。看你的要求。确定最佳方法。
标签: javascript oop reactjs redux react-redux