首页 > 解决方案 > 在组件 B 中使用组件 A 的返回值

问题描述

我有以下组件。

//Component A

import * as React from "react";

interface IProps {
  length: number;
  width: number;
}

export default function Test(props: IProps) {
  const { length, width } = props;
  const someNumber = 12;
  let returnNum: number = 0;
  returnNum = (length * width );

  return <> { returnNum } </>; 
}

我想返回returnNum到以下组件

// Component B

import * as React from "react";

interface IProps {
    returnNum: number;
}

export default function GetValueToThisFunction(props: IProps) {
    const { returnNum } = props;
    let valueRet = 0;
    if (returnNum < 1) {
        valueRet = 400;
    } else if (returnNum >= 1 && returnNum < 2) {
        valueRet = 300;
    }
}

我正在通过以下方式使用我的组件

<Test length={18} width={3}/>
<GetValueToThisFunction returnNum={} />;

我基本上想传递Test组件返回值(returnNum)并将其用于GetValueForThisFunction

标签: reactjs

解决方案


您可以使用更高阶的组件来呈现您的组件。

const withArea = Component => ({ length, width }) => (
    <Fragment>
        {/* render whatever you want here */}
        <Component area={length * width} />
    </Fragment>
);

const ComponentWithArea = withArea(MyComponent);

const App = () => (
    <ComponentWithArea length={5} width={10} />
)

推荐阅读