代码之家  ›  专栏  ›  技术社区  ›  Sandro_V

按下React Native(反应)按钮不起作用

  •  1
  • Sandro_V  · 技术社区  · 7 年前

    我无法将onPress方法绑定到JSX按钮。 我已经尝试了很多不同的解决方案,但都没有成功。

    onPress方法:

    class ScreenEnterPlayerNames extends Component {
    
      constructor(props) {
        super(props);
      }
    
      static navigationOptions = {
        title: 'Player Names',
      };
    
      onPressStartTheGame = () => {
        console.log("Pushed button Start the Game!")
        //dispatch({ type: ADD_PLAYER_NAME, playerNumber: 5, playerName: "Sandro" })
      }
    

    按钮:

    return (
          <View style={styles.viewMain}>
            <View style={styles.viewTxt}>
              <Text style={styles.TxtHeading}>
                Please enter the names in sequence.
              </Text>
            </View>
            <ScrollView style={styles.viewTextBox}>
              {textBoxes}
            </ScrollView>
    
            <View style={styles.viewButton}>
              <Button
                title='Start the Game!'
                onPress={() => this.onPressStartTheGame}
              />
            </View>
          </View>
        );
      }
    }
    

    我也尝试过以下方法:

    onPress={this.onPressStartTheGame}
    onPress={this.onPressStartTheGame()}
    onPress={this.onPressStartTheGame.bind(this)}
    onPress={() => this.onPressStartTheGame.bind(this)}
    

    我尝试将函数更改为:

    onPressStartTheGame()  {...
    

    所以我很确定还有其他问题,但我不知道是什么。

    谢谢!:-)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Paulquappe    7 年前

    试试你的方法

     onPressStartTheGame(){
        console.log("Pushed button Start the Game!")
        //dispatch({ type: ADD_PLAYER_NAME, playerNumber: 5, playerName: "Sandro" })
      }
    

    并这样称呼它

    onPress={this.onPressStartTheGame.bind(this)}
    

    在这里,您可以再次检查并尝试在沙盒中进行操作。 https://facebook.github.io/react-native/docs/handling-touches.html