我正在尝试构建一个包含react中的组件数组的组件,根据元素的总数为数组中的每个组件提供一个新的大小。但是视图不会更新所有组件。即使我每次都重建数组,也只更新新添加的组件大小。
class StampArea extends React.Component{
constructor(props){
super(props);
this.state = {updateView: true};
this.getStampSize = this.getStampSize.bind(this);
this.prepareStamps = this.prepareStamps.bind(this);
this.balance = 1;
}
prepareStamps(fulfill){
var stamps = [];
console.log('stamps: ', stamps);
for (var i = 1; i <= fulfill; i++) {
if(i<=this.balance){
stamps.push(<Stamp key={i} stampSize={this.getStampSize(fulfill)} stamped={true} stampBackgroundImage={this.props.stampBackgroundImage} stampPunchImage={this.props.stampPunchImage}/>);
}else{
stamps.push(<Stamp key={i} stampSize={this.getStampSize(fulfill)} stamped={false} stampBackgroundImage={this.props.stampBackgroundImage} stampPunchImage={this.props.stampPunchImage}/>);
}
}
console.log('stamps: ', stamps);
return(stamps);
}
getStampSize(fulfill){
if(fulfill >= 20){return 10}
if(fulfill >= 15){return 20}
if(fulfill >= 10){return 50}
if(fulfill >= 8 ){return 35}
if(fulfill >= 5 ){return 40}
if(fulfill >= 4 ){return 60}
if(fulfill >= 1 ){return 80}
}
render(){
return( <div style={styles.stampsContainer}>{this.prepareStamps(this.props.fulfill)}</div>);
}
}
class Stamp extends React.Component{
constructor(props){
super(props);
this.stamp=null;
this.buildStamp=this.buildStamp.bind(this);
this.buildStamp();
}
buildStamp(){
// Assigning correct stylesheet to build the stamp as asked.
if(this.props.stamped){
this.punched = (<img style={{position:'absolute',height:this.props.stampSize, width:this.props.stampSize, resizeMode:'contain'}} src={this.props.stampPunchImage}/>);
}else{
this.punched = null;
}
console.log('stampsize inside, ', this.props.stampSize);
this.backgroundImage = (<img style={{position:'absolute',height:this.props.stampSize, width:this.props.stampSize, resizeMode:'contain'}} src={this.props.stampBackgroundImage}/>);
this.stamp = (<div style={{position:'relative', margin:5,height:this.props.stampSize, width:this.props.stampSize}}>{this.backgroundImage}{this.punched}</div>);
}
render(){
return(this.stamp);
}
}
以下是一些可以更好地解释的照片,
The initial state always renders correct
This is how it looks when i update the component via props
此外,当我检查数组对象时,我看到大小道具设置了正确的值,但不知何故它没有正确呈现。
我该如何解决这个问题?
答案 0 :(得分:0)
这是因为你的render方法只返回this.stamp
,它只在构造函数中生成一次。