簡體   English   中英

如何在不調用的情況下傳遞函數/閉包?

[英]How to pass function/closure without calling it?

我正在嘗試設置一個狀態,它恰好是 react-native 中的一個函數,如下所示:

...
    setSendFunction(function () {
        console.log('HELLO');
    });

但是每次運行此行時,都會打印“HELLO”,這是我不想要的。 我只想將此匿名函數存儲在某處而不運行它。

正如@Bergi 所說,你想做類似的事情

import React, { useState } from "react";

export default function App() {
//here func() will give you the value of 5
  const [func, setFunc] = useState(() => () => 5);

  const handleClick = (num) => {
// after this, func() will provide new value, which is num
    setFunc((prevState) => () => prevState() + num);
  };
  return (
    <div>
      <h2>{func()} </h2>
      <button onClick={(e) => handleClick(10)}> Change State</button>
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM