我正在使用打字稿反应。我有一个函数返回jsx中的组件:
function TestComponent(str: string) {
return <span>Hello, your string was {str}</span>
}
假设该函数合理(是吗?),如何在更多jsx代码中调用它?
我试过了:
<TestComponent str="abcde" />
<TestComponent str={'abcde'} />
<TestComponent {'abcde'} />
<TestComponent {str:'abcde'} />
但是我怀疑我缺少关于函数参数如何传递的更根本的东西(我对React和Typescript都非常陌生)。
谢谢。
您非常接近,面临的问题是,即使传递单个项目,道具还是一个对象。
interface TestComponentProps {
str: string;
}
function TestComponent({str}: TestComponentProps) {
return <span>Hello, your string was {str}</span>
}
然后,您可以使用以下两种语法之一对其进行调用:
<TestComponent str='abcde' />
<TestComponent str={'abcde'} />
str={'abcde'}
仅仅意味着React应该评估'abcde'
。由于它是字符串文字,因此没有任何变化。但是,这有一个重要的警告,字符串文字没有应用任何HTML转义。因此,您必须自己处理。
React文档在解释这里发生的事情方面做得很好。但简而言之,JSX只是语法糖,这些等同于编写:
React.createElement(TestComponent, {str: 'abcde'}, null);
由此,您可能会猜测如果我们添加第二个道具会发生什么。
interface TestComponentProps {
str: string;
coolString: string;
}
function TestComponent({str, coolString}: TestComponentProps) {
return <span>Hello, your string was {str} and your coolString was {coolString}</span>
}
<TestComponent str="abcde" coolString={'fghi'}/>
那么,第三个参数是什么?那是给孩子的。这个答案被偷了给孩子打字。让我们来看看它的作用。
interface TestComponentProps {
str: string;
children: React.ReactNode
}
function TestComponent({str, children}: TestComponentProps) {
return (<>
<span>Hello, your string was {str}</span>
<div>
{children}
</div>
</>);
}
<TestComponent str={'<3'}>
<p>Hey there! 1 + 1 = {1 + 1}</p>
<p>I'm another child!</p>
</TestComponent>
成为:
function TestComponent({
str,
children
}) {
return React.createElement(React.Fragment, null, React.createElement("span", null, "Hello, your string was ", str), React.createElement("div", null, children));
}
React.createElement(TestComponent, {
str: '<3'
}, React.createElement("p", null, "Hey there! 1 + 1 = ", 1 + 1), React.createElement("p", null, "I'm another child!"));
注意:该<>
</>
语法称为Fragment,本质上是一个没有DOM输出的分组函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句