[英]Typescript calling a function by reference inside of react jsx
I am using Typescript with React JS.我正在使用 Typescript 和 React JS。
let's say if I have a React functional component:假设我有一个 React 功能组件:
function MyFunction(){
const myArrowFunction = () =>{
return(
<div>
<p>Some Paragraph</p>
</div>
);
};
//In JavaScript, I would do this to call it the function by reference and it works.
//In TypeScript, when I do the same, I do not see the "Some Paragraph" visible on the screen
return(
<main>
{myArrowFunction}
</main>
);
}
calling the function with parenthesis works in Typescript:用括号调用函数在 Typescript 中有效:
return(
<main>
{myArrowFunction()}
</main>
);
In JavaScript, I would do this {myArrowFunction} to call it the function by reference and it works.在 JavaScript 中,我会这样做 {myArrowFunction} 以通过引用调用它的函数并且它有效。 In TypeScript, when I do the same, I do not see the "Some Paragraph" visible on the screen
在 TypeScript 中,当我执行相同操作时,我在屏幕上看不到“某些段落”
What is the best way to call a function by reference in Typescript?在 Typescript 中通过引用调用函数的最佳方式是什么?
Thanks.谢谢。
What you are doing is wrong even in js
即使在
js
中,你所做的也是错误的
I know what you want to do and you could call this as below, but it is not recommended to create a component inside a component我知道你想做什么,你可以这样称呼它,但不建议在组件内部创建组件
function MyFunction(){
const myArrowFunction = () =>{
return(
<div>
<p>Some Paragraph</p>
</div>
);
};
// this is manly to stop typescript from complaining
const Fn = myArrowFunction as any;
return(
<main>
<Fn />
</main>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.