【发布时间】:2021-06-18 14:08:16
【问题描述】:
可以导出功能组件内部的功能并且可以导入到另一个功能组件中吗? 示例代码: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
App.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>
);
}
【问题讨论】:
-
如果要导出功能需要将其移出组件
-
您找到解决方案了吗?遇到同样的问题
-
嗨 Katharina,就我而言,我使用自定义钩子解决了这个问题,允许您导出具有所有逻辑的组件,另一个选项可以是:stackoverflow.com/questions/37949981/…
-
尝试查看 useImperativeHandle 钩子。你可以在这里读到它。 stackoverflow.com/questions/57005663/…