【问题标题】:how can I pass a single argument to a react function that returns a component?如何将单个参数传递给返回组件的反应函数?
【发布时间】:2021-01-02 18:06:28
【问题描述】:

我正在使用对打字稿做出反应。我有一个在 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 都很陌生)。

谢谢。

【问题讨论】:

  • 我没有时间写一个完整的答案,但是你做的是一个组件,第一个参数是props 对象。如果您将签名更改为TestComponent({ str })(即使用解构),那么它应该可以工作。我将把它留给你来输入......关于如何在功能组件中输入道具有不同的看法。

标签: reactjs typescript


【解决方案1】:

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

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!"));

注意:&lt;&gt; &lt;/&gt; 语法称为 Fragment,本质上是一个没有 DOM 输出的分组函数。

【讨论】:

    【解决方案2】:

    尝试让你的函数接受一个 props 对象作为参数,并在 span 元素中使用 {props.str}。或者解构参数中的str prop。

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多