React:从另一个组件调用函数(具体示例)

React: Calling Function From Another Component (Specific Example)

我想更好地理解 React,所以我做了这个玩具示例来尝试让 React 组件从另一个组件调用函数。我正在 Chrome 上查看 React Dev 工具,但没有任何内容被记录到控制台。我不确定为什么会这样。有人可以向我解释为什么这是错误的以及如何解决它吗?

TestButton.js 文件

import React from 'react';
import Button from '@material-ui/core/Button';

export default function TestButton() {
  return(
    <div>
      <Button
    id='searchButton'
    variant="contained"
    color="primary"
    type="submit"
    fullWidth
    onClick={testFunction}
  >
    Search
  </Button>
    </div>
  );
}

App.js 文件:

import './App.css';
import Header from './components/Header.js';
import TestButton from './components/TestButton.js';

function testFunction() {
  console.log("Yay it works!");
}

function App() {
  return (
    <div className="App">
      <Header />
      <TestButton></TestButton>
    </div>
  );
}

export default App;

您需要将 testFunction 的引用从 App 传递到 TestButton。像这样:

export default function TestButton({fn}) {
  return(
    <div>
      <Button
        id='searchButton'
        variant="contained"
        color="primary"
        type="submit"
        fullWidth
        onClick={fn}
      >
        Search
      </Button>
    </div>
  );
}

function App() {
  function testFunction() {
    console.log("Yay it works!");
  }
  return (
    <div className="App">
      <Header />
      <TestButton fn={testFunction}></TestButton>
    </div>
  );
}

按照您的方式,testFunction 不在 TestButton 组件的范围内,因此传递一个您的 TestButton 可以用作回调的函数是实现此目的的一种方法。

您的 App 组件需要显式地将函数引用传递给 TestButton 组件:

<TestButton testFunction={testFunction}></TestButton>

并且您的 TestButton 组件需要接受传递给它的 属性 对象。从那里你可以解构函数并使用它。

export default function TestButton({ testFunction }) {