不确定是不是(评估“this.state.starSide”)

问题描述:

这是我的代码的对象:不确定是不是(评估“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://*.com/questions/37123387/this-state-is-undefined-during-onpress-event-in-react-native) – kas

您必须将此绑定到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

你应该使用时绑定上下文处理程序的JSX当您设置onPress道具不调用该方法,只是通过参考吧:

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

感谢您的帮助 – RichardSleet

阵营处理程序不会自动绑定到元/类,他们是

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

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

感谢您的帮助 – RichardSleet

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

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

然后:

<TouchableOpacity onPress={this.addStar}>