繁体   English   中英

在反应中的功能组件内导出 function

[英]Export function inside functional component in react

是否可以导出功能组件内部的 function 并且可以导入另一个? 示例代码: 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

组件二:

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

const componentTwo = () => {

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

    </div>
  )
}

export default componentTwo

应用程序.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>
  );
}

可以从功能组件中导出 function 以供父组件使用。

您所要做的就是充分利用 refs。

见下面的例子:

组件一

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;

组件二

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;

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

你可以这样做:

组件一:

import React from "react";

export function hello() {
  console.log("Hello, says the componentOne");
}

const componentOne = () => {
  return <div></div>;
};

export default componentOne;

组件二:

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

const componentTwo = () => {
  return (
    <div>
      <button onClick={hello}>Hello</button>
    </div>
  );
};

export default componentTwo;

应用程序.js

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

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

这里是一个例子: https://codesandbox.io/s/focused-forest-zncxn?file=/src/App.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM