You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何为组件Touchable传入函数类型Props?

解决方案

1. 重构BookTile组件,支持传入点击事件Props

修改BookTile组件,让它接收图书标题、标题点击回调、阅读按钮点击回调等Props,同时把标题和阅读按钮的Touchable元素整合到组件内部,避免外部重复编写:

const BookTile = (props) => {
    return (
        <View>
            {/* 可点击的图书标题 */}
            <TouchableWithoutFeedback onPress={props.onTitlePress}>
                <Text style={props.titleStyle}>
                    {props.title}
                </Text>
            </TouchableWithoutFeedback>
            
            <View style={styles.bookoverview}>
                <Text style={styles.bookauthor}>van {props.author}</Text>
                <Text style={styles.description}>{props.description}</Text>
                <Text style={styles.isbn}>ISBN {props.isbn}</Text>
            </View>
            
            {/* 可点击的阅读按钮 */}
            <TouchableHighlight 
                underlayColor="lightgrey" 
                onPress={props.onReadPress} 
                style={styles.tile}
            >
                <View>
                    <Text style={styles.tileText}>GELEZEN</Text>
                </View>
            </TouchableHighlight>
        </View>
    );
}

// 需提前导入依赖组件
// import { View, Text, TouchableWithoutFeedback, TouchableHighlight } from 'react-native';

export default BookTile;

2. 在父组件中使用BookTile并传入点击函数

在父组件里直接调用BookTile,把标题、对应的点击函数作为Props传入即可,无需再单独编写Touchable元素:

// 父组件中的使用示例
<BookTile 
    title="Iene Miene Mutte"
    titleStyle={styles.booktitle}
    author="M.J. Arlidge" 
    description="Het meisje was..." 
    isbn="978-9-0225-7622-9"
    onTitlePress={() => title1()}
    onReadPress={() => book1()}
/>

补充说明

  • 如果需要在点击函数中传递图书相关参数(如书名、ISBN),可以通过箭头函数包裹传参:
    // 父组件定义带参数的函数
    function titlePress(bookTitle) {
      console.log(`${bookTitle} - TITEL GEKLIKT`);
    }
    
    // 传入组件时
    onTitlePress={() => titlePress("Iene Miene Mutte")}
    
  • 若无需传参,也可直接传递函数引用(不用箭头函数),但传参时必须用箭头函数包裹,否则函数会在组件渲染时立即执行。

内容的提问来源于stack exchange,提问作者EviVermeeren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:45:31