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

React Render Prop问题:为何传入的函数未被调用?

问题原因与修复方案

问题核心在于React Native的Button组件没有handleSelect这个点击触发属性,你把子组件传递的handleSelect函数绑定到了一个不存在的props上,所以点击按钮时自然不会执行这个函数。React Native的按钮点击回调是通过onPress属性指定的。

修复后的代码

父组件(Parent)

const Parent = () => {
    return (
        <View>
            <Selector
                render={({handleSelect}) => {
                    // 把handleSelect绑定到Button的onPress属性上
                    return <Button
                        title="select"
                        onPress={handleSelect}
                    />
                }}
            />
        </View>
    )
}

子组件(Selector)

const Selector = ({render}) => {
    const handleSelect = (input) => {
        console.log("helllooo") // 现在点击按钮会执行这段代码了
    };
    
    return (
        <View>
            {render({handleSelect: handleSelect})}
            <View><Text>other content here...</Text></View>
        </View>
    )
};

额外说明

如果需要给handleSelect传递自定义参数,可以用箭头函数包裹:

// 父组件里的Button部分
return <Button
    title="select"
    onPress={() => handleSelect('自定义参数')}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:50:22