用 debounce 反应回调:子组件没有将回调返回给父组件

我想在debounce 按下按钮时包含该功能。


我已经debounce在ChildComponent. 它可以工作,ChildComponent但我没有收到回调ParentComponent。


家长:


<MyButton onPress={() => alert("My Button clicked")} />

孩子:


const MyButton = props => {

  const {title = 'Enter', style = {}, textStyle = {}, onPress} = props;

  const delayedOnPress = useCallback(

    debounce(() => {

      console.log(onPress);

      return onPress;

    }, 500),

    [],

  );


  const onPressed = () => {

    return delayedOnPress();

  };


  return (

    <TouchableOpacity onPress={onPressed} style={[styles.button, style]}>

      <Text style={[styles.text, textStyle]}>{title}</Text>

    </TouchableOpacity>

  );

};

谁能更新我我做错了什么?


凤凰求蛊
浏览 195回答 1
1回答

人到中年有点甜

一些注意点:在里面使用箭头函数useCallback。无需在内部debounce和处理程序函数中返回任何内容。import React, { useCallback } from "react";import "./styles.css";import { TouchableOpacity, Text } from "react-native";import { debounce } from "lodash";const debounceAction = debounce(e => {&nbsp; console.log(e);&nbsp; &nbsp;// "My Button clicked"&nbsp; alert(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// "My Button clicked"}, 500);const MyButton = props => {&nbsp; const { onPress } = props;&nbsp; const delayedOnPress = useCallback(e => debounceAction(e), []);&nbsp; const onPressed = () => {&nbsp; &nbsp; delayedOnPress(onPress);&nbsp; };&nbsp; return (&nbsp; &nbsp; <TouchableOpacity onPress={onPressed}>&nbsp; &nbsp; &nbsp; <Text>Button</Text>&nbsp; &nbsp; </TouchableOpacity>&nbsp; );};export default function App() {&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <MyButton onPress="My Button clicked" />&nbsp; &nbsp; </div>&nbsp; );}更新如果我们想从父级传递一个自定义函数作为道具:const debounceAction = debounce(e => {&nbsp; e();&nbsp; &nbsp; &nbsp; &nbsp;// customized function been passed}, 500);...export default function App() {&nbsp; const customizedFunction = () => { // customized function&nbsp; &nbsp; alert("test");&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <MyButton onPress={customizedFunction} />&nbsp; // notice no `()` here&nbsp; &nbsp; </div>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript