如何使用反应功能组件动态设置道具名称
How to dynamically set prop names using react functional components
const handleStyle = () => {
if (!props.hoverTxt) {
return { display: "none" };
} else {
return {};
}
};
return (
<div>
<HeroAsideItems txt={props.hoverTxt} style={handleStyle()} />
</div>
);
}
export default HeroAsideCircles;
这是我的代码。下面是我希望能工作的伪代码。简而言之,我想动态设置一个道具名称,这样我就可以让 hoverTxt 设置函数参数,所以如果我将 1 传递给 handleStyles 函数,它将 return props.hovertxt1 或者如果我将参数设置为 6
const handleStyle = (tEXTnUMBER) => {
if (!props.hoverTxt + tEXTnUMBER) {
return { display: "none" };
} else {
return {};
}
};
return (
<div>
<HeroAsideItems txt={props.hoverTxt5} style={handleStyle(5)} />
</div>
);
}
export default HeroAsideCircles;
道具也是一个对象,您可以使用字符串访问对象键,例如
const obj = { name: 'Gwen' };
console.log(obj['name']);
基于此,您可以使用确切的方法来访问您的道具名称
const handleStyle = (numberTxt) => {
if (!props[`hoverTxt${numberTxt}`]) {
return { display: "none" };
} else {
return {};
}
};
return (
<div>
<HeroAsideItems txt={props.hoverTxt5} style={handleStyle(5)} />
</div>
);
const handleStyle = () => {
if (!props.hoverTxt) {
return { display: "none" };
} else {
return {};
}
};
return (
<div>
<HeroAsideItems txt={props.hoverTxt} style={handleStyle()} />
</div>
);
}
export default HeroAsideCircles;
这是我的代码。下面是我希望能工作的伪代码。简而言之,我想动态设置一个道具名称,这样我就可以让 hoverTxt 设置函数参数,所以如果我将 1 传递给 handleStyles 函数,它将 return props.hovertxt1 或者如果我将参数设置为 6
const handleStyle = (tEXTnUMBER) => {
if (!props.hoverTxt + tEXTnUMBER) {
return { display: "none" };
} else {
return {};
}
};
return (
<div>
<HeroAsideItems txt={props.hoverTxt5} style={handleStyle(5)} />
</div>
);
}
export default HeroAsideCircles;
道具也是一个对象,您可以使用字符串访问对象键,例如
const obj = { name: 'Gwen' };
console.log(obj['name']);
基于此,您可以使用确切的方法来访问您的道具名称
const handleStyle = (numberTxt) => {
if (!props[`hoverTxt${numberTxt}`]) {
return { display: "none" };
} else {
return {};
}
};
return (
<div>
<HeroAsideItems txt={props.hoverTxt5} style={handleStyle(5)} />
</div>
);