【问题标题】:React: How can I pass a value to my main App() functionReact:如何将值传递给我的主 App() 函数
【发布时间】:2021-03-26 07:28:19
【问题描述】:

我有一个 react 应用程序,我想将一个值(“groupId”)传递给主应用程序组件。

我的应用组件定义为function App()。我尝试使用以下方式传递参数值:

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import './scss/index.scss';
import App from './App';

const targetDivName= 'myapp-ui';
const targetDiv = document.getElementById(targetDivName);
const groupId: string = targetDiv?.getAttribute("data-group-id") ?? '';

ReactDOM.render(
  <React.StrictMode>
    <App groupId={ groupId } />
  </React.StrictMode>,
  targetDiv
);

App.tsx:

import React from "react";
import { Box } from "./components/Box";
import styles from './scss/App.module.scss';

function App(groupId: string) {
    return (
        <div className={ styles.orchestratorUi }>
          <Box groupId={ groupId } />
        </div>
    );
}

export default App;

但这会产生以下错误(编译并运行):

Type '{ groupId: string; }' is not assignable to type 'string'.ts(2322)

如何通过我的 App() 将 HTML 代码中的值传递到主组件(本例中为 Box)。

【问题讨论】:

  • 请记住 props 是作为对象传递的,而不是单个参数。

标签: reactjs typescript create-react-app react-component


【解决方案1】:

你需要改变

function App(groupId: string) {

到

function App({groupId}: any) {

甚至更好

interface Props {
  groupId: string
}

function App({ groupId }: Props) {

您的代码发生的情况是 typescript 将 function App(groupId: string) { 中的 groupId 解释为 string 类型,而是在您实例化 App 时接收一个对象。

在你的例子中,这个对象是{"groupId": groupId},其中groupId是你在App.tsx中分配的变量。

【讨论】:

  • 谢谢,按照您的示例(以及部分其他示例)使其正常工作。
【解决方案2】:

这是因为 React 组件接受 props 作为对象。

首先,需要像这样从 props 对象中获取groupId:

function App({ groupId }) {

Here你可以找到函数组件的类型。

所以定义 App 组件接受的 props 的正确方法是:

import React from "react";
import { Box } from "./components/Box";
import styles from './scss/App.module.scss';

interface AppProps {
  groupId: string;
}

// React.FC is an alias for React.FunctionComponent
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/v16/index.d.ts#L544
const App: React.FC<AppProps> = ({ groupId }) => {
  return (
    <div className={ styles.orchestratorUi }>
      <Box groupId={ groupId } />
    </div>
  );
};

export default App;

【讨论】:

    【解决方案3】:

    您的索引很好,您的主要组件应该是这样的: 功能应用程序(道具){ . . . .

    【讨论】:

      【解决方案4】:

      props 是作为 object 传递的,所以改变

      function App(groupId: string) {
      

      到

      //                    vvvvvvvvvvvvvvvvvvv−−−−−− declaring the type of props
      function App({groupId}: {groupId: string}) {
      //           ^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−− using destructuring
      

      这将App 的第一个参数声明为{groupId: string} 类型,并使用解构从道具中获取groupId。

      【讨论】:

      • 感谢您提及解构概念。
      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2022-01-13
      • 2021-06-01
      • 2022-12-12
      相关资源
      最近更新 更多