簡體   English   中英

從組件React Native內部訪問狀態

[英]Accessing state from within component React Native

我是本機的新手,在使用RkButton的應用程序上進行響應,然后在單擊按鈕時更新狀態。 代碼是這樣的。

 render() { const { user } = this.props; let navigate = this.props.navigation.navigate; let items = MainRoutes.map(function (route, index) { return ( <RkButton rkType='square' key={index} onPress={() => { this.setState({ redeem: true }); }}> </RkButton> ) }); return ( <View style={{flex: 1,}}> <ScrollView alwaysBounceVertical overScrollMode={"always"} style={{flex: 1, backgroundColor: 'white'}} refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={() => this.handleRefresh()} /> } contentContainerStyle={styles.rootContainer}> {items} </ScrollView> </View> ) } 

我得到“ this.setState不是函數”,因為我使用了UIKitten庫中的代碼,所以我並不完全熟悉它。 我很確定這與ES6有關,或者我對組件的工作方式有誤解。

有人可以啟發我嗎?

您在此處松開Components上下文:

  // Component context
  function (route, index) {
    // Functions context

更改為:

  (route, index) => {

問題在於用關鍵字function聲明的function具有它自己的上下文this 您需要使用箭頭功能來訪問父上下文:

let items = MainRoutes.map((route, index) => {
  return (
    <RkButton
      rkType='square'
      key={index}
      onPress={() => {
          this.setState({
            redeem: true
          });
      }}>
    </RkButton>
  )
});

您應該保留這個副本,並使用它的任何其他函數中。 如需要,如第3行所述。

所以你的代碼有一些小的變化

render() {
    const { user } = this.props;
    let self=this;

    let navigate = this.props.navigation.navigate;

    let items = MainRoutes.map(function (route, index) {
      return (
        <RkButton
          rkType='square'
          key={index}
          onPress={() => {
              self.setState({
                redeem: true
              });
          }}>
        </RkButton>
      )
    });

      return (
        <View style={{flex: 1,}}>
            <ScrollView
              alwaysBounceVertical
              overScrollMode={"always"}
              style={{flex: 1, backgroundColor: 'white'}}
              refreshControl={
                  <RefreshControl
                  refreshing={this.state.refreshing}
                  onRefresh={() => this.handleRefresh()}
                  />
              }
              contentContainerStyle={styles.rootContainer}>
                {items}
            </ScrollView>
          </View>
      )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM