使用 TouchableWithoutFeedback 反应原生 onPress 不起作用

Wai*_*ein 25 react-native touchablewithoutfeedback

我正在开发一个用于学习目的的简单 React Native 应用程序。我只是迈出了进入 React Native 世界的第一步。但是在这个非常早期的阶段,我遇到了问题。我无法让简单的触摸事件工作。我正在使用 TouchableWithoutFeedback 实现触摸事件。这是我的代码。

class AlbumList extends React.Component {

    constructor(props)
    {
        super(props)
        this.state = {
            displayList : true
        }
    }
    componentWillMount() {
        this.props.fetchAlbums();
    }

    albumPressed(album)
    {
        console.log("Touch event triggered")
    }

    renderAlbumItem = ({item: album}) => {
        return (
                <TouchableWithoutFeedback onPress={this.albumPressed.bind(this)}>
                    <Card>
                        <CardSection>
                            <Text>{album.artist}</Text>
                        </CardSection>
                        <CardSection>
                            <Text>{album.title}</Text>
                        </CardSection>
                    </Card>
                </TouchableWithoutFeedback>
            )
    }

    render() {
        let list;
        if (this.state.displayList) {
            list = <FlatList
                data={this.props.albums}
                renderItem={this.renderAlbumItem}
                keyExtractor={(album) => album.title}
            />
        }

        return (
            list
        )
    }
}

const mapStateToProps = state => {
    return state.albumList;
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return bindActionCreators({
        fetchAlbums : AlbumListActions.fetchAlbums
    }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(AlbumList);
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在列表项上实现触摸事件。但是当我在模拟器上点击卡片时它根本没有触发。为什么?我该如何解决?

小智 41

您应该像这样将内容包装在组件中:

<TouchableWithoutFeedback>
 <View>
  <Your components...>
 </View>
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

  • [github问题](https://github.com/facebook/react-native/issues/10180#issuecomment-298375648)已经在评论中讨论过。也许您可以填写其他详细信息,以便将所有内容集中在一处。简单地发布没有解释的代码片段几乎没有帮助。 (3认同)

Nab*_*l K 16

TouchableWithoutFeedback总是需要有子View组件。所以一个组成 a 的组件View是不够的。

所以代替

<TouchableWithoutFeedback onPressIn={...} onPressOut={...} onPress={...}>
  <MyCustomComponent />
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

用:

<TouchableWithoutFeedback onPressIn={...} onPressOut={...} onPress={...}>
  <View>
    <MyCustomComponent />
  </View>
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅github 问题


Avi*_*jit 7

可以与 <TouchableOpacity activeOpacity={1.0}> </TouchableOpacity>