React:如何将值传递给我的主应用程序()函数



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

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

索引.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
);

应用程序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)

如何通过应用程序((将HTML代码中的值传递到主组件(本例中为Box(。

道具作为对象传递,因此更改

function App(groupId: string) {

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

它声明App的第一个参数为{groupId: string}类型,并使用析构函数从props获取groupId

您需要更改

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中指定的变量。

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

首先,有必要从如下道具对象中获取groupId

function App({ groupId }) {

在这里,您可以找到功能组件的类型。

因此,App组件接受的定义道具的正确方法是:

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;

您的索引很好,您的主要组件应该如下:功能应用程序(道具({。。。.