2017-10-08 30 views
0

我想傳遞一個參數給我的函數,但每當我加載頁面這個get的調用。我也試過()=> this.loadStories('bloomberg'),但這似乎沒有工作。這是我的代碼。React本機onPress正在加載調用

class Main extends Component { 

constructor() { 
    super(); 
    this.loadStories = this.loadStories('channel').bind(this); 
} 

componentDidMount(){ 

} 

loadStories(channel) { 
    this.props.getStories(channel); 
} 

render() { 
    return (
    <ScrollView> 
     <View style={{marginTop: 20}}> 

     <Button onPress={this.loadStories('bloomberg')} title="Top Stories"></Button> 


     {this.props.stories.map(function(item, index){ 
     return(
      <View key={index} style={{marginBottom: 10, padding: 10}}> 
      <Text>{item.title}</Text> 
      <Text>{item.description}</Text> 
      </View> 
     ) 
     })} 
    </View> 

    </ScrollView> 
); 
} 
} 
+0

改變它想:'onPress = {()=> this.loadStories( '彭博' )}'以防止立即調用 – Cherniv

回答

1

您可以執行以下操作以防止直接方法(函數)調用的問題,您有:

class Main extends Component { 
    constructor() { 
    // Step #1: Delete this line. You can't bind like this. 
    // this.loadStories = this.loadStories('channel').bind(this); 
    } 

    /* ... */ 

    render() { 
    return (
     <ScrollView> 
     <View style={{marginTop: 20}}> 
      { /* Step #2: bind inline and pass 'bloomberg' like so: */ } 
      <Button onPress={this.loadStories.bind(this, 'bloomberg')} title="Top Stories"> 
      </Button> 
     </View> 

     { /* ... */ } 
     </ScrollView> 
    ); 
    } 
}