我正在使用带有typescript的react。我有一个函数,它返回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输出的分组函数。
试着让函数接受一个props对象作为参数,并在span元素中使用{props.str}。或者对参数中的str-prop进行反结构。