您已经很接近了,您面临的问题是即使您传递单个项目,道具也是一个对象。
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 转义。所以你必须自己处理。
The React documentation 很好地解释了这里发生的事情。但简而言之,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'}/>
那么,第三个参数是什么?那是给孩子的。此answer 中的儿童打字被盗。让我们看看它的实际效果。
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 输出的分组函数。