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

按React Native调用函数

  •  11
  • Somename  · 技术社区  · 9 年前

    我只是想知道如何调用函数 onPress 。我的代码设置如下:

    export default class Tab3 extends Component {
        constructor(props) {
            super(props);
            this.state = {myColor: "green"};
        }
    
        handleClick = () => {
            if (this.state.color === 'green'){
               this.setState({myColor: 'blue'});
            } else {
               this.setState({myColor: 'green'});
            }
        }
    
        render() {
         return(
          <View>
               <Icon
                name='heart'
                color={this.state.myColor}
                size= {45}
                style={{marginLeft:40}}
                onPress={() => handleClick(this)}                                 
                />
          </View>
          )};
    

    can't find variable handleClick

    5 回复  |  直到 9 年前
        1
  •  13
  •   evanmcdonnal    9 年前

    在渲染过程中,处理程序设置不正确,请尝试一下;

     <View>
           <Icon
            name='heart'
            color={this.state.myColor}
            size= {45}
            style={{marginLeft:40}}
            onPress={this.handleClick}                                 
            />
      </View>
    

    您使用的语法对于内联声明匿名函数或其他东西很有意义,但由于处理程序是在类上定义的,因此您只需使用 this.functionName 在道具中。

        2
  •  12
  •   Community Mohan Dere    7 年前

    派对有点晚了,但如果有人需要的话,我想把这个留在这里

    export default class mainScreen extends Component {
    
    handleClick = () => {
     //some code
    }
    
    render() {
     return(
      <View>
           <Button
            name='someButton'
            onPress={() => {
                this.handleClick(); //usual call like vanilla javascript, but uses this operator
             }}                                 
            />
      </View>
      )};
    
        3
  •  3
  •   Miguel    9 年前

    this 关键字。

     <Icon
        onPress={this.handleClick}                                 
      />
    
        4
  •  0
  •   SHREYA PRASAD    8 年前

    this.handleClick = this.handleClick.bind(this) 
    

    并将其放入构造函数中。调用时使用此语法

    onPress = {this.handleClick}
    

        5
  •  0
  •   Guilhermy    6 年前

    如果您没有使用类组件,那么只需删除 这

    此函数可以处理任何路由的导航(只要有一个屏幕的名称作为参数传递),无需多个处理程序。

    const navigation = useNavigation(); 
    
    function handleNavigation(route) {
        navigation.navigate(route);
    }
    

    <Button onPress={() => handleNavigation("Menu")} ></Button>