[英]Passing down function from parent to child through React functional component
I am trying to pass down the functions setDir
and handleSort()
down from SearchAppointments
(parent) to Hooks
(child), but I keep getting errors saying that they are not functions.我正在尝试将函数
setDir
和handleSort()
从SearchAppointments
(父)传递给Hooks
(子),但我不断收到错误消息,说它们不是函数。
I tried to debug it by looking the typeof
handleSort
in the useEffect
hook of the child component, though it console.logged two statements: 1) underfined 2) function.我试图通过查看子组件的
useEffect
钩子中的typeof
handleSort
来调试它,尽管它在控制台记录了两个语句:1)underfined 2)function。 Not sure what is wrong.不知道出了什么问题。
const SearchAppointments = React.memo(() => {
const [orderDir, setDir] = useState("");
const handleSort = (e) => {
let value = e.target.value;
setDir(value);
let order;
let filterData = data;
if (orderDir === 'asc') {
order = 1;
} else {
order = -1;
}
};
return (
<>
<div>
<Hooks handleSort={handleSort} setDir={setDir} />
</div>
</>
);
});
const Hooks = React.memo(({ handleSort, setDir }) => {
useEffect(() => {
console.log(typeof handleSort);
}, []);
return (
<div>
<div>
<button type="button" onClick={() => setDir("success")}>
Set Dir
</button>
<button type="button" value='asc' onClick={handleSort}>
Handle Sort (Asc)
</button>
<button type="button" value='dsc' onClick={handleSort}>
Handle Sort (Dsc)
</button>
</div>
</div>
);
});
try and use memo
like this:尝试像这样使用
memo
:
const comparator = (previous, next) => {
if (something) {
return true
}
return false
}
const Hooks = React.memo(({ handleSort, setDir }) => {
useEffect(() => {
console.log(typeof handleSort);
}, []);
return (
<div>
<div>
<button type="button" onClick={() => setDir("success")}>
Set Dir
</button>
<button type="button" value='asc' onClick={handleSort}>
Handle Sort (Asc)
</button>
<button type="button" value='dsc' onClick={handleSort}>
Handle Sort (Dsc)
</button>
</div>
</div>
);
}, comparator);
define a function and pass that as the second argument.定义一个 function 并将其作为第二个参数传递。
memo
function (I've called it comparator
, then returns true
or false
depending on when you want the component to update. think of it as the new shouldComponentUpdate
in the lifecycle methods. but use with care as your application might not update if you use carelessly memo
comparator
(我称它为 compare ,然后根据您希望组件更新的时间返回true
或false
。将其视为生命周期方法中的新shouldComponentUpdate
。但请小心使用,因为如果您使用,您的应用程序可能不会更新不小心
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.