0

对于 onClick 事件,我需要调用嵌套在另一个方法中的方法。React 代码基于 React Hooks。

应用程序.js

import ..........
bla bla bla

const App = () => {
  const a = () => {
    const b = () => {
      console.log("Testing")
    }
  }
  return (
    <Button onClick={()=>b()}>
      Click Me
    </Button>
  )
}

对于上面的这个例子,我需要调用 b() onClick。因为在我真正的应用程序中,b() 方法依赖于 a() 方法中的某些东西。如何做到这一点?

4

2 回答 2

1

你也可以这样做:

const a = () => {
    // do your regular stuff
    return () => {
      console.log("Testing")
    }
}

<button onClick={()=>a()()}>

您可以通过“运行代码片段”查看

const App = () => {
  const a = () => {
    return () => {
      console.log("Testing")
    }
  }
  
  const a2 = () => {
    const b = () => {
      console.log("Testing from @giorgim")
    }
    return {b}
  };

  return (
    <div>
    <button onClick={()=>a()()}>
      Click Me
    </button>
    <br/><br/>
    <button onClick={()=>a2().b()}>
      Click Me Via @giorgim
    </button>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

于 2020-05-13T09:51:17.440 回答
-1

我通过 setState 在 b() 方法中解决了这个问题。并分别从 b() 重用它。谢谢大家的支持

于 2020-05-13T10:38:51.860 回答