[英]Call a function inside const React/Typescript
In my application, I want to conditionally render something, so I made a function getItem
which I want to call in my custom Tooltip, const CustomTooltip
.在我的应用程序中,我想有条件地渲染一些东西,所以我创建了一个函数
getItem
,我想在我的自定义工具提示const CustomTooltip
中调用它。
How can I call the function with the return
of my custom tooltip?如何在
return
自定义工具提示的情况下调用该函数? Currently, it render getState("A"), getState("B"), getState("C"), on the tooltip.目前,它在工具提示上呈现 getState("A")、getState("B")、getState("C")。 See code below:
请参见下面的代码:
const numberStates = 3;
function getState({payload}: TooltipProps<ValueType, NameType>, state: string ){
if(payload){
for(let i = 0; i < numberStates; i++){
if(payload[i].dataKey == state){
return <p>{ payload[i] } : { payload[i].value }</p>
}
}
}
return null;
}
const CustomTooltip = ({ active, payload, label}: TooltipProps<ValueType, NameType>) => {
if(active && payload && payload.length){
return (
<div className = "custom-tooltip">
getState("A")
getState("B")
getState("C")
</div>
);
}
return null;
}
You need to surround your calls to getState
in brackets:您需要将调用
getState
括在括号中:
const CustomTooltip = ({ active, payload, label}: TooltipProps<ValueType, NameType>) => {
if(active && payload && payload.length){
return (
<div className = "custom-tooltip">
{getState("A")}
{getState("B")}
{getState("C")}
</div>
);
}
return null;
You should expect to use this syntax if you're trying to utilize any javascript functionalities within the JSX.如果您尝试使用 JSX 中的任何 javascript 功能,您应该期望使用此语法。
More information can be found here regarding functions in react.可以在此处找到有关 react 中的功能的更多信息。 You can scroll down to the "Example: Passing params using arrow functions" section and see an example of how brackets are necessary for using a map on the state.
您可以向下滚动到“示例:使用箭头函数传递参数”部分,并查看如何在状态上使用地图时需要括号的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.