我的组成如下:
const HookComponent = (props)=> {
let [month, changeMonth] = useState(moment());
return (
<ChildComponent
month={month}
onChange={m => changeMonth(m)}
minStep={5}
prevMonthIcon="ion-ios-arrow-left"
nextMonthIcon="ion-ios-arrow-right"
/>
)
}
ChildComponent是一个类组件,它使用setState更新月份。上面的问题是更改没有反映在DOM上,但是父组件中的状态正在更改(通过用户输入-按钮更改了ChildComponent中的状态)。我记录了下来,并确认父母的月份在变化。在挂钩中使用类组件时,react的某些限制吗?
当我将HookComponent转换为类组件并使用setState更改月份时,它按预期方式工作,并且DOM在输入更改时发生更改。
[InputMoment
组件似乎没有使用month
道具,而是使用了moment
道具。
[而且,似乎InputMoment
返回的时刻与moment
属性传递的实例相同。这导致执行changeMonth
语句时,由于引用未更改,因此不会重新呈现元素。
您可以通过在状态下存储对象来解决此问题。调用changeMonth
时,您传递了一个新对象,然后正确重新渲染了InputMoment
:
const HookComponent = (props)=> {
let [month, changeMonth] = useState({ m: moment() });
return (
<ChildComponent
moment={month.m}
onChange={m => changeMonth({ m })}
minStep={5}
prevMonthIcon="ion-ios-arrow-left"
nextMonthIcon="ion-ios-arrow-right"
/>
)
}