【问题标题】:How to call a component onPress TouchableOpacity in react-native如何在 react-native 中调用组件 onPress TouchableOpacity
【发布时间】:2021-06-12 15:28:23
【问题描述】:

我正在使用 react-native 的 TouchableOpacity。代码是:

<TouchableOpacity onPress={onPress}>
    <Text style={styles.supplementItem}>{item.item}</Text>
</TouchableOpacity>

OnPress 函数在哪里:

 const onPress = () => (
  // eslint-disable-next-line no-sequences
  <Text style={styles.supplementItem}>Hello</Text>
  this.setState({tempKey: tempKey + 1})
);

我看了看:this question 并尝试做喜欢它。但这不起作用。我将状态设置如下:

constructor(props) {
super(props);
this.state = {
  tempKey: 0,
};

}

请帮助我做错了什么。

【问题讨论】:

    标签: react-native components touchableopacity onpress


    【解决方案1】:

    您提到的问题是使用基于函数的组件,而您正在使用基于类的组件,因为您展示了证明这一点的 costructor 部分。

    所以onPress在你的情况下必须是那个类中的一个方法,所以你不需要const之前的关键字,你需要以这种方式调用它; this.onPress

    简而言之,你的整个组件应该是这样的;

    import React from 'react';
    import {Text, TouchableOpacity, View} from 'react-native';
    
    class YourComp extends React.Component {
        constructor(props) {
        super(props);
        this.state = {
          tempKey: 0,
          show: false
        };
        
        }
        onPress = () => {
          // eslint-disable-next-line no-sequences
          this.setState(prevState => ({tempKey: prevState.tempKey + 1}))
        };
    
    render() {
       return (
    <View>
        <TouchableOpacity style={{height: 100, justifyContent: 'center', alignItems: 'center'}} onPress={() => this.onPress()}>
            <Text>Hello (item.item in your case)</Text>
        </TouchableOpacity>
    
          <Text key={this.state.tempKey.toString()}>Hello {this.state.tempKey}</Text>
    </View>
      )
    
    
    }
    
    
    }
    export default YourComp;
    

    如果你想有条件地显示某些组件;

    this.state = {
          ...,
         show: false
    
    }
    

    然后在onPress方法中;

    this.setState(prevState => ({show: !prevState.show})) // this will make <Text /> to toggle the modal when clicked.
    

    然后在render方法中;

    <Text>
      {this.state.show && (
        <YourNewComponent />
    
    ) || null}
    
    
    </Text>
    

    【讨论】:

    • 我试过这个解决方案。但我什么也没得到
    • 这里的项目是什么以及为什么要在印刷机上显示文本组件
    • 编辑了我的答案。检查这是否是您想要的。如果没有,请评论缺少的内容。如果您需要解释也可以评论
    • 这也不起作用。实际上我想在按下这个 组件时调用一个模态组件。但我希望模态组件位于单独的文件中
    • 您可以创建另一个状态变量,并在单击 时将其设置为 true,并在此基础上使模式可见....
    猜你喜欢
    • 2021-05-08
    • 2018-08-20
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    相关资源
    最近更新 更多