在react中导出功能组件内的函数

JGP*_*ode 3 export function reactjs

是否可以导出功能组件内部的函数并可以将其导入到另一个组件中?示例代码: https: //codesandbox.io/s/blissful-sanne-chk5g ?file=/src/App.js:0-275

第一部分:

import React from 'react'

const componentOne = () => {

    function hello(){
    console.log("Hello, says the componentOne")
  }
  return (
    <div>
      
    </div>
  )
}

export default componentOne
Run Code Online (Sandbox Code Playgroud)

第二部分:

import React from 'react'
import {hello} from "./ComponentOne"

const componentTwo = () => {

   
  return (
    <div>
      
    <button
    onClick={hello}>
        Hello
    </button>

    </div>
  )
}

export default componentTwo
Run Code Online (Sandbox Code Playgroud)

应用程序.js

import ComponentTwo from "./components/ComponentTwo";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <ComponentTwo />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

小智 9

可以从功能组件导出函数以便由父组件使用。

您所要做的就是充分利用参考文献。

请参阅下面的示例:

组成部分一

import React, { forwardRef, useImperativeHandle } from "react";

const ComponentOne = forwardRef((props, ref) => {
    useImperativeHandle(ref, () => ({
        hello() {
            console.log("Hello, says the componentOne");
        }
    }));

    return (
        <div></div>
    );
});

export default ComponentOne;
Run Code Online (Sandbox Code Playgroud)

第二部分

import React { useRef } from "react";
import ComponentOne from "./ComponentOne";

const ComponentTwo = () => {
    const componentOneRef = useRef(null);
    const componentOne = <ComponentOne ref={ componentOneRef } />;
   
    return (
        <div>
            <button onClick={ () => componentOneRef.current.hello() }>Hello</button>
        </div>
    );
}

export default componentTwo;
Run Code Online (Sandbox Code Playgroud)

让我补充一下,在您的示例中,您似乎不想渲染 ComponentOne,而只想使用其中的 hello 函数。如果是这种情况,函数组件可能不是您真正想要的:您可能会考虑创建一个实用的 javascript 文件,在其中导出函数。