我有以下内容。
//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
答案 0 :(得分:1)
您可以使用higher order component来渲染组件。
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} />
)
答案 1 :(得分:0)
从您的代码中,我了解到<Test>
和<GetValueToThisFunction>
是兄弟姐妹。我将更改<Test>
组件,添加一个新的回调道具:
//Component A
import * as React from "react";
interface IProps {
length: number;
width: number;
updateNum: (num: number) => void; // 1. Add new callback props
}
export default function Test(props: IProps) {
const { length, width, updateNum } = props;
const someNumber = 12;
let returnNum: number = 0;
returnNum = (length * width );
updateNum(returnNum); // 2. Call the new callback, passing in input the returnNum
return <> { returnNum } </>;
}
现在,您可以使用回调保存从returnNum
返回的<Test>
,将其保存到状态,然后使用状态将其传递到<GetValueToThisFunction>
:
<Test length={18} width={3} updateNum={(newNum) => this.setState({newNum})}/>
<GetValueToThisFunction returnNum={this.state.newNum} />
答案 2 :(得分:-1)
import * as React from "react";
import B from "path/to/B";
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 <B returnNum={returnNum}/>;
}