[英]How can I use a function from another file in react?
我想為執行此操作的函數創建一個文件(function.js):
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}
然后我想將它添加到 (this.js)
import function from "./function";
class Example extends Component {
state = {
test
};
render() {
function()
return (
<div>
<h1>{this.state.test.sample[i].name}</h1>
</div>
你可以這樣做:
function.js
const doSomething = function() {
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}
}
export default doSomething;
App.js(例如):
import doSomething from "./function";
class Example extends Component {
state = {
test
};
render() {
doSomething()
return (
<div>
<h1>{this.state.test.sample[i].name}</h1>
</div>
)
function
關鍵字是保留標識符。
在瀏覽器上,您需要某種捆綁工具,它允許從js模塊import
。 在服務器上,您只require(path/to/file)
。 我建議您查看create-react-app
以獲得完整的功能react
設置。 基本設置包含有關JS模塊系統的示例(請參閱下面的文檔)。
作為回報,您的文件需要導出您要使用的符號。
在具有a.js
和b.js
的目錄中,其中b
想要從a
導入符號
// file a.js
export function myFunction () {}
// file b.js
import { myFunction } from "./a";
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://github.com/facebook/create-react-app
function.js
有以下代碼
const funcName = function() {
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}
}
export default funcName;
你可以在this.js
使用它,如下所示 -
import funcName from "./function";
class Example extends Component {
state = {
test
};
render() {
funcName()
return (
<div>
<h1>{this.state.test.sample[i].name}</h1>
</div>
)
在function.js中導出你的函數
export function funcName() {
//function stuff
let i = 1;
return i;
}
進口將是
import { funcName } from './function';
console.log(`value of i is ${funcName()}`);
有多種方法可以做到這一點。
如果要在該文件中創建多個函數
export const one = () => {
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}
}
export const two = () => {
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}
}
然后導入並使用它
import {
one,
two
} from "./functions"
您可以使用export defualt
export default = function() {
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}
}
然后通過這樣做簡單地使用它
import function from "./function";
試試這個
另一個文件.js
export function sum(a, b) {
return a + b;
}
export function ShowText() {
return '<h1>This is a sample Page</h1>';
}
應用程序.js
import {sum, ShowText} from './another-file';
export default function App() {
return (
<div>
<h2>5 + 5 = {sum(5, 5)}</h2>
<hr />
<h2>Text From another file: {ShowText()}</h2>
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.