当子组件是变量时反应传递道具
React pass props when child component is a variable
当组件是变量时,如何将 props 传递给子组件。在下面的代码中,我需要将 prev 函数作为 prop 传递给步骤。谢谢
import React, {useState} from 'react';
const Wizard = (props)=>{
const [step] = useState(0);
const CurrStep = props.steps[step];
const prev = ()=>{
console.log('prev called')
}
return (
<div>
{// need to pass prev as a prop to the CurrStep component}
{CurrStep }
</div>)
}
export default Wizard
Wizard.propTypes = {
header: PropTypes.func.isRequired,
steps: PropTypes.array.isRequired,//array of functional components
wizardContext: PropTypes.object.isRequired,
onComplete: PropTypes.func.isRequired
};
// adding (props) =>
const CurrStep = (...props) => props.steps[step](...props);
const prev = () => {
console.log('prev called')
}
return (
<div>
{CurrStep(prev)}
</div>
)
您可以像这样在 CurrStep
组件内展开 props
return <CurrStep {...props} />;
下面是 codesandbox 代码演示
import React, { useState } from "react";
const Wizard = props => {
const [step] = useState(0);
const Comp1 = props => <div>{props.a}</div>;
const Comp2 = props => <div>{props.a}</div>;
const comps = [Comp1, Comp2];
const CurrStep = comps[step];
// this is just for demo, you can just pass props straight from Wizard
props = { a: "a", ...props };
return <CurrStep {...props} />;
};
export default Wizard;
这是我的错误,我传递的数组是这样的:
[ ] 而不是
[第一步,第二步]
抱歉浪费您的时间。
当组件是变量时,如何将 props 传递给子组件。在下面的代码中,我需要将 prev 函数作为 prop 传递给步骤。谢谢
import React, {useState} from 'react';
const Wizard = (props)=>{
const [step] = useState(0);
const CurrStep = props.steps[step];
const prev = ()=>{
console.log('prev called')
}
return (
<div>
{// need to pass prev as a prop to the CurrStep component}
{CurrStep }
</div>)
}
export default Wizard
Wizard.propTypes = {
header: PropTypes.func.isRequired,
steps: PropTypes.array.isRequired,//array of functional components
wizardContext: PropTypes.object.isRequired,
onComplete: PropTypes.func.isRequired
};
// adding (props) =>
const CurrStep = (...props) => props.steps[step](...props);
const prev = () => {
console.log('prev called')
}
return (
<div>
{CurrStep(prev)}
</div>
)
您可以像这样在 CurrStep
组件内展开 props
return <CurrStep {...props} />;
下面是 codesandbox 代码演示
import React, { useState } from "react";
const Wizard = props => {
const [step] = useState(0);
const Comp1 = props => <div>{props.a}</div>;
const Comp2 = props => <div>{props.a}</div>;
const comps = [Comp1, Comp2];
const CurrStep = comps[step];
// this is just for demo, you can just pass props straight from Wizard
props = { a: "a", ...props };
return <CurrStep {...props} />;
};
export default Wizard;
这是我的错误,我传递的数组是这样的:
[ ] 而不是
[第一步,第二步]
抱歉浪费您的时间。