如何将单个参数传递给返回组件的反应函数?

Jer*_*Jer 3 typescript reactjs

我正在使用带有打字稿的反应。我有一个返回 jsx 中的组件的函数:

function TestComponent(str: string) {
    return <span>Hello, your string was {str}</span>
}
Run Code Online (Sandbox Code Playgroud)

假设该函数是合理的(是吗?),我如何在更多 jsx 代码中调用它?

我努力了:

  <TestComponent str="abcde" />
  <TestComponent str={'abcde'} />
  <TestComponent {'abcde'} />
  <TestComponent {str:'abcde'} />
Run Code Online (Sandbox Code Playgroud)

但我怀疑我错过了一些关于函数参数如何传递的更基本的东西(我对反应和打字稿都很陌生)。

谢谢。

Dig*_*ion 5

你已经很接近了,你面临的问题是,即使你传递单个项目,道具也是一个对象。

interface TestComponentProps {
   str: string;
}
function TestComponent({str}: TestComponentProps) {
    return <span>Hello, your string was {str}</span>
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下任一语法来调用它:

<TestComponent str='abcde' />
<TestComponent str={'abcde'} />
Run Code Online (Sandbox Code Playgroud)

str={'abcde'}只是意味着 React 应该评估'abcde'. 由于它是字符串文字,因此没有任何变化。然而,这有一个重要的警告,字符串文字没有应用任何 HTML 转义。所以你必须自己做这个处理。

React 文档很好地解释了幕后发生的事情。但简而言之,JSX 只是语法糖,这些相当于编写:

React.createElement(TestComponent, {str: 'abcde'}, null);
Run Code Online (Sandbox Code Playgroud)

由此,您可能可以猜到如果我们添加第二个 prop 会发生什么。

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'}/>
Run Code Online (Sandbox Code Playgroud)

那么,第三个参数是什么呢?那是给孩子们的。为儿童打字是从这个答案中偷来的。让我们看看它的实际效果。

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>
Run Code Online (Sandbox Code Playgroud)

变成:

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!"));
Run Code Online (Sandbox Code Playgroud)

注意:该<> </>语法称为Fragment,本质上是一个没有 DOM 输出的分组函数。