这些是我的代码:
class StarListScrollViewCell extends Component{
static propTypes = {
dateSource : React.PropTypes.array
}
constructor(props){
super(props);
this.state = {
starSide : 20,
}
}
addStar(){
LayoutAnimation.spring();
this.setState({starSide: this.state.starSide + 10});
}
componentWillMount() {
LayoutAnimation.spring();
}
render(){
return(
<View style={{backgroundColor: 'white' , height: 70 , width : Dimensions.get('window').width,flexDirection:'row'}}>
<TouchableOpacity style={{backgroundColor: 'red' ,width:Dimensions.get('window').width/7,justifyContent:'center',alignItems:'center'}}
onPress = {this.addStar()}>
<Image source={require('./star-gray.png')}
style ={{width:this.state.starSide,
height:this.state.starSide,
justifyContent:'center',alignItems:'center'}}>
</Image>
</TouchableOpacity>
</View>
);
}
}
单击按钮时遇到了一个错误。然后写它引用https://facebook.github.io/react-native/releases/next/next/docs/animations.html
您必须将其绑定到AddStar,因为从事件处理程序打电话时,此上下文会更改。
constructor(props){
super(props);
this.state = {
starSide : 20,
}
this.addStar = this.addStar.bind(this);
}
<TouchableOpacity onPress = {this.addStar()}>
上面的线路也可以正常运行,但会立即称为您的目的,因此可以使用
<TouchableOpacity onPress = {this.addStar}>
在JSX中使用处理程序时,应将上下文绑定到 onPress
prop时不要调用该方法,只需传递参考:
<TouchableOpacity style={{backgroundColor: 'red' ,width:Dimensions.get('window').width/7,justifyContent:'center',alignItems:'center'}}
onPress = {this.addStar.bind(this)}>
React处理程序未自动绑定到它们所在的元素/类。
将onPress = {this.addStar()}>
更改为
onPress = {this.addStar.bind(this)}>
而不是绑定,您只能使用箭头函数:
addStar = () => {
LayoutAnimation.spring();
this.setState({starSide: this.state.starSide + 10});
}
,然后:
<TouchableOpacity onPress={this.addStar}>