在加载时调用React Native onPress

时间:2017-10-08 14:35:25

标签: reactjs react-native react-native-ios

我正在尝试将参数传递给我的函数,但每当我加载页面时,都会调用此函数。我也试过()=> this.loadStories(' bloomberg')但这似乎不起作用。这是我的代码。

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

1 个答案:

答案 0 :(得分: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>
    );
  }
}
相关问题