【问题标题】:React Native onClick is not firingReact Native onClick 没有触发
【发布时间】:2020-01-28 15:44:23
【问题描述】:

在使用 NativeBase 为 Android 开发 React Native 应用程序时,我遇到了一个问题。尽管使用了箭头函数,但我的 Button 组件中的 onClick() 事件没有触发,我不知道为什么。

代码如下:

import React from 'react';
import {View, Text} from 'react-native';
import {withNavigation} from 'react-navigation';
import {Button, Header, Icon, Item, Input} from 'native-base';

let text = '';

class SearchBar extends React.Component {
  onButtonClick = () => {
    text = 'yes';
  };

  render() {
    return (
      <View>
        <Header searchBar rounded>
          <Item>
            <Icon name="ios-search" />
            <Input placeholder="Search" />
          </Item>
        </Header>
        <Button onClick={() => this.onButtonClick()}>
          <Text>Search</Text>
        </Button>
        <Text>Is the button clicked? {text}</Text>
      </View>
    );
  }
}

export default withNavigation(SearchBar);

你能帮帮我吗?在所有其他组件中,我实现了与上面示例完全相同的事件功能,并且这些功能正在运行。上面那个有什么问题?

我还尝试了来自 React-Native 而不是 NativeBase 的 Button - 同样的问题。

【问题讨论】:

    标签: react-native native-base


    【解决方案1】:

    在本机反应中称为“onPress” 参考:https://facebook.github.io/react-native/docs/0.58/button

    【讨论】:

    • 我在 5 分钟前遇到了这个问题 :)
    【解决方案2】:

    只有当状态改变时才会更新反应组件。 在这里,您的 text 变量发生了变化,但您的 react 组件不知道它必须更新。

    您应该使用onPress 而不是onClick 并这样做以触发重新渲染(更新状态):

    import React from 'react';
    import {View, Text} from 'react-native';
    import {withNavigation} from 'react-navigation';
    import {Button, Header, Icon, Item, Input} from 'native-base';
    
    
    class SearchBar extends React.Component {
      constructor(props) {
        super(props);
        this.state = {text: ''};
      }
    
      onButtonClick = () => {
        this.setState({text: 'yes'});
      };
    
      render() {
        return (
          <View>
            <Header searchBar rounded>
              <Item>
                <Icon name="ios-search" />
                <Input placeholder="Search" />
              </Item>
            </Header>
            <Button onPress={() => this.onButtonClick()}>
              <Text>Search</Text>
            </Button>
            <Text>Is the button clicked? {this.state.text}</Text>
          </View>
        );
      }
    }
    
    export default withNavigation(SearchBar);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2021-09-27
      相关资源
      最近更新 更多