這是我的代碼的一部分:
const currentPrice = useRef(null);
const [currentPriceTooltip, setCurrentPriceTooltip] = useState(0);
useEffect(() => {
if (props.instrument) {
setRange(props.instrument);
}
}
const setRange = (instrument) => {
const currentPricePosition =
rangeInfo.HighestTradePrice > rangeInfo.UpperStaticThreshold
? ((rangeInfo.LastTradePrice - rangeInfo.LowerStaticThreshold) /
(rangeInfo.HighestTradePrice - rangeInfo.LowerStaticThreshold)) *
100
: ((rangeInfo.LastTradePrice - rangeInfo.LowerStaticThreshold) /
(rangeInfo.UpperStaticThreshold - rangeInfo.LowerStaticThreshold)) *
100;
currentPrice.current.style.left = `${currentPricePosition}%`;
setCurrentPriceTooltip( comma(rangeInfo.LastTradePrice))
currentPrice.current.children[0].style.fill =
rangeInfo.LastTradePrice > rangeInfo.PreviousDayPrice
? `${theme.palette.color.green}`
: `${theme.palette.color.red}`;
}
return (
<>
<Tooltip
placement="top"
title={currentPriceTooltip}
>
<Grid
item
className={classes.currentPrice}
ref={currentPrice}
onClick={() => clickHandler(currentPriceTooltip)}
>
<LocationIcon
className={clsx(
classes.currentPriceIcon,
device.isMobile && classes.currentPriceIconMobile
)}
></LocationIcon>
</Grid>
</Tooltip>
</>
)
我想直接在 Dom 上設定而不使用 state。如何使用 useRef 我不想擁有 state 。這就是我所做的:
const setRange = (instrument) => {
////The things above
currentPrice.current.value = comma(rangeInfo.LastTradePrice);
}
<Tooltip
placement="top"
title={currentPrice.current.value}
>
我第一次無法在工具提示中使用它
uj5u.com熱心網友回復:
由于要使用 useRef 掛鉤來更新 tooltip 內容,因此需要使用一些 DOM 操作方法來更新 tooltip 內容,所以如果您像這樣更新 ref 值:
tooltipRef.current = "updated value"
它只會更新 tooltipRef 物件的當前值,并且不會反映在 UI 上,正如您所知,react DOM 僅在完成任何狀態或道具更改時才會更新。
所以要使用 useRef 鉤子來實作同樣的效果,我們需要借助組件的一些道具
<div className="App">
<Tooltip PopperProps={{disablePortal:true, keepMounted: true}} onOpen={(e) => {
e.target.nextElementSibling.querySelector("div").innerHTML = toolTipRef.current
}}>
<div>Tooltip</div>
</Tooltip>
</div>
這里我們使用了一些 PopperProps
- disablePortal: true => 將此設定為 true 將在同一 html div 中而不是在外部附加工具提示標記
- KeepMounted: true => 將其設為 true 將始終使標記 div 可用
因此,在完成上述活動之后,我們將使用 onOpen 方法訪問工具提示參考 div,因此通過使用它可以訪問實際的工具提示內容 div 并更新我們存盤在 tooltipRef 變數內部的內容。
要在此處檢查作業演示是參考鏈接 CodeSandbox
uj5u.com熱心網友回復:
currentPrice.current
從 DOM 中賦予價值
您可以使用相同的方法設定值
例如
currentPrice.current= "Any value you want"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495674.html
標籤:javascript 反应 dom 反应钩子
上一篇:如何從我的串列中洗掉某些元素Javascripthtml
下一篇:單擊相應按鈕隱藏影像