[英]Increase number by click in react.js
我正在react.js
编写一个Product
组件,并且当单击该项目时,我想增加实际产品的inCartCount
值。
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Product.css';
var NumberFormat = require('react-number-format');
class Product extends React.Component {
addToCart(product) {
console.log(product.inCartCount);
product.inCartCount++;
}
render() {
const product = this.props.data;
product.inCartCount = product.inCartCount || 0;
return (
<div onClick={this.addToCart.bind(this, product)}>
<h3>{product.name}</h3>
<NumberFormat value={product.price} displayType={'text'} thousandSeparator={true} suffix={' Ft'}/>
<span>{product.inCartCount}</span>
</div>
);
}
}
export default withStyles(s)(Product);
在console.log
该值正在增加,但未呈现为DOM
,我始终在浏览器inCartCount
值视为0
。
您不能像使用代码那样使用代码。 要增加计数器,您应该使用this.state.counter
并在您的组件中使用此变量。 因为每次this.state
更改时,您的组件都会自动重新呈现并采用新的this.state
。 如果您只是手动更改值,您将执行此操作-组件不会重新呈现,并且您永远不会在页面上看到更改后的值。 但是不要忘记this.state = {counter: 0};
首先在方法getInitialState()
这样的:
getInitialState() {
return { counter: 0 };
}
并将其用于render
方法或类似this.state.counter
任何方法
每次从道具获取产品都是不可变的,并且永远不会更新,这里有2个选项:
问题是您每次都在渲染中重新初始化产品,可能的解决方案:
在父组件中:
<Product
updateProduct={this.updateProduct.bind(this)}
data={this.state.data}
/>
updateProduct(value){
this.setState({data:value});
}
在子组件中:
addToCart(product) {
console.log(product.inCartCount);
product.inCartCount++;
this.props.updateProduct(product);
}
2.将产品以状态存储在子组件上,如下所示:
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Product.css';
var NumberFormat = require('react-number-format');
class Product extends React.Component {
constructor(props) {
super(props);
this.state = {
product: props.data
};
}
addToCart() {
let product = this.state.product;
product.inCartCount = product.inCartCount ? product.inCartCount+1 : 1;
this.setState({product});
}
render() {
return (
<div onClick={this.addToCart.bind(this)}>
<h3>{this.state.product.name}</h3>
<NumberFormat value={this.state.product.price} displayType={'text'} thousandSeparator={true} suffix={' Ft'}/>
<span>{this.state.product.inCartCount}</span>
</div>
);
}
}
export default withStyles(s)(Product);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.