2017-02-15 83 views
1

這是我的代碼的對象:不確定是不是(評估「this.state.starSide」)

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> 
    ); 
} 

}

我遇到了一個錯誤,當我點擊button.And我把它寫引用https://facebook.github.io/react-native/releases/next/docs/animations.html

+0

正如@ owaishanif786提到你需要綁定的方法到當前組件,而且當你調用它的時候:'onPress = {this.addStar}'沒有括號 – Hosar

+0

[this.state在反應原生中的onPress事件期間未定義]的可能重複(https://stackoverflow.com/questions/37123387/this-state-is-undefined-during-onpress-event-in-react-native) – kas

回答

1

您必須將此綁定到addStar,因爲當您從事件處理程序調用此上下文時發生更改。

constructor(props){ 
    super(props); 
    this.state = { 
     starSide : 20, 
    } 

    this.addStar = this.addStar.bind(this); 


} 

<TouchableOpacity onPress = {this.addStar()}> 

也高於線將會運行得很好,但它會被稱爲立即可這是不是你的目的,所以改用

<TouchableOpacity onPress = {this.addStar}> 
+0

感謝您的幫助! – RichardSleet

0

你應該使用時綁定上下文處理程序的JSX當您設置onPress道具不調用該方法,只是通過參考吧:

<TouchableOpacity style={{backgroundColor: 'red' ,width:Dimensions.get('window').width/7,justifyContent:'center',alignItems:'center'}} 
      onPress = {this.addStar.bind(this)}> 
+1

感謝您的幫助 – RichardSleet

0

陣營處理程序不會自動綁定到元/類,他們是

變化onPress = {this.addStar()}>

onPress = {this.addStar.bind(this)}> 
+0

感謝您的幫助 – RichardSleet

0

取而代之的結合,你可以只使用箭頭功能:

addStar =() => { 
    LayoutAnimation.spring(); 
    this.setState({starSide: this.state.starSide + 10}); 
} 

然後:

<TouchableOpacity onPress={this.addStar}> 
相關問題