需要在父组件中将状态传递给子组件,并通过钩子函数来修改子组件的状态。代码示例如下:
父组件:
import React, { useState } from 'react';
import { Steps } from 'antd';
const { Step } = Steps;
const ParentComponent = () => {
const [currentStep, setCurrentStep] = useState(0);
const handleNext = () => {
setCurrentStep(currentStep + 1);
}
return (
)
}
export default ParentComponent;
子组件:
import React, { useState, useEffect } from 'react';
import { Steps } from 'antd';
const { Step } = Steps;
const ChildComponent = ({ currentStep }) => {
const [stepStatus, setStepStatus] = useState({ 0: 'process', 1: '', 2: '' });
useEffect(() => {
const newStatus = { ...stepStatus };
for (let i = 0; i < currentStep; i++) {
newStatus[i] = 'finish';
}
newStatus[currentStep] = 'process';
setStepStatus(newStatus);
}, [currentStep])
return (
)
}
export default ChildComponent;
在子组件中,通过使用useEffect
来监听父组件传来的currentStep
值的变化,并根据变化来修改步骤状态。这样就可以在子组件中正确地渲染步骤状态了。