如何通过不变部分访问名称动态变化的reactProps变量
动态后缀ReactProps变量的引用方案
如果你的目标变量挂在全局对象(比如浏览器的window)上,可以通过遍历属性、匹配固定前缀的方式找到它:
// 假设变量名的固定前缀是'reactProps$',后面跟着动态内容 let targetProps = null; // 遍历全局对象的所有属性 for (const key in window) { // 匹配名称里的不变部分 if (key.startsWith('reactProps$')) { targetProps = window[key]; break; // 找到目标就停止遍历,避免多匹配 } } // 拿到变量后就可以正常使用了 if (targetProps) { console.log(targetProps); }
要是变量在局部作用域里(不是全局),可以把当前作用域的变量转成对象遍历,但这里要用到eval,注意它有安全风险,谨慎使用:
function getTargetReactProps() { let targetProps = null; // 获取当前作用域的所有变量名 const scopeKeys = Object.getOwnPropertyNames(this); for (const key of scopeKeys) { if (key.startsWith('reactProps$')) { targetProps = eval(key); break; } } return targetProps; }
另外提个更稳妥的思路:如果能接触到组件的上下文,优先从组件的props或者state里直接取数据,别依赖这种动态命名的变量——毕竟网站代码更新可能随时改变量名前缀,这种正规渠道的兼容性会好很多。
内容的提问来源于stack exchange,提问作者Vakarine
相关产品推荐
相关产品推荐

