react:从另一个组件调用函数(特定示例)

x7rlezfr  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(442)

我试图更好地理解react,所以我制作了这个玩具示例,试图让react组件从另一个组件调用函数。我正在查看chrome上的react-dev工具,但控制台上没有任何记录。我不知道为什么会这样。有人能给我解释一下为什么这是错误的,以及如何修复它吗?
testbutton.js文件

  1. import React from 'react';
  2. import Button from '@material-ui/core/Button';
  3. export default function TestButton() {
  4. return(
  5. <div>
  6. <Button
  7. id='searchButton'
  8. variant="contained"
  9. color="primary"
  10. type="submit"
  11. fullWidth
  12. onClick={testFunction}
  13. >
  14. Search
  15. </Button>
  16. </div>
  17. );
  18. }

app.js文件:

  1. import './App.css';
  2. import Header from './components/Header.js';
  3. import TestButton from './components/TestButton.js';
  4. function testFunction() {
  5. console.log("Yay it works!");
  6. }
  7. function App() {
  8. return (
  9. <div className="App">
  10. <Header />
  11. <TestButton></TestButton>
  12. </div>
  13. );
  14. }
  15. export default App;
5lwkijsr

5lwkijsr1#

您需要传递对的引用 testFunction 从…起 App 进入 TestButton . 大概是这样的:

  1. export default function TestButton({fn}) {
  2. return(
  3. <div>
  4. <Button
  5. id='searchButton'
  6. variant="contained"
  7. color="primary"
  8. type="submit"
  9. fullWidth
  10. onClick={fn}
  11. >
  12. Search
  13. </Button>
  14. </div>
  15. );
  16. }
  17. function App() {
  18. function testFunction() {
  19. console.log("Yay it works!");
  20. }
  21. return (
  22. <div className="App">
  23. <Header />
  24. <TestButton fn={testFunction}></TestButton>
  25. </div>
  26. );
  27. }

按照您的方式,testfunction不在 TestButton 组件,所以传入testbutton可以用作回调的函数是实现这一点的一种方法。

展开查看全部

相关问题