我正在構建一個天氣應用程式,其中有一個索引頁面,每小時顯示一堆卡片。我有一個值(無論是 AM 還是 PM),我將其存盤在 useref 中并將其傳遞給子組件。當滿足某些條件時,從子級呼叫 onChange 函式(該函式存在于父級中)并更改 useref 的值,但子級中的值沒有改變。這堆卡片是通過映射顯示的,所以我期待如果父級中的 userref 值發生更改,下一張卡片將獲得更改后的值,但這不會發生。我使用 useref 錯誤嗎?index.js
import type { NextPage } from 'next'
import WeatherCard from '../components/WeatherCard'
import { motion } from 'framer-motion'
import { useEffect, useRef, useState } from 'react'
import { PropsType } from '../types'
const Home: NextPage<PropsType> = (props) => {
const [time,setTime]=useState(new Date());
const timeFormatRef=React.useRef(new Date().toLocaleString('en-US',
{hour: 'numeric', hour12: true }).split(' ')[1]) as any;
const onTimeFormatChange=()=>{
if(timeFormatRef.current==='AM')
timeFormatRef.current='PM'
else
timeFormatRef.current='AM';
}
return (
<div className=>
<main>
{determineWeatherCardsArr().map((el,index)=>{
return <motion.div>
<WeatherCard key={index} weather={el.weather}
temp={el.temp} index={index}
time={time} ref={timeFormatRef}
onTimeFormatChange= {onTimeFormatChange}/>
</motion.div>})
</main>
</div>
)
}
export default Home
WeatherCard.js
import Image from "next/image";
const WeatherCard:React.forwardref=(props,ref)=>{
const determineHour=(time:Date):string=>{
let amPmTimeArr=time.toLocaleString('en-US',
{ hour: 'numeric', hour12: true }).split(' ');
let hour
[hour]=[...amPmTimeArr]
if( hour props.index>=12){
hour=( hour props.index)%12;
if( hour===0){
props.onTimeFormatChange();//changing the useref here
}
return hour ref.current;
}
else{
hour= hour props.index
return hour ref.current;
}
}
let cardTitle=determineHour(props.time)
return(
<div className="">
<h3 className="">{cardTitle}</h3>
</div>
)
}
uj5u.com熱心網友回復:
React 不會對 ref 值更改做出“反應”,因此如果 ref 值更改,您的子組件將不會被重新渲染。使用狀態變數來實作
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490122.html
標籤:javascript 反应 参考 使用参考
