我已经浏览过https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
我很好奇是否有更好的方法将当前单击的面板名称传递给handlePanelClick()
。 let currentPanel = eval(
this.${name}Panel);
行是我关心的。
我需要评估name
,然后将其设置为currentPanel 的一部分。如果我将 eval()
删除为 'this.${name}Panel'
,那么 currentPanel
就不是 DOM 元素。
这是使用 eval() 的正确用例吗?
export default class Profiles extends Component {
constructor(props) {
super(props);
this.ul, this.hunterPanel, this.fieldPanel, ...
// other declarations...
this.handlePanelClick = this.handlePanelClick.bind(this);
}
handlePanelClick(event, name) {
event.preventDefault();
const currentScrollPosition = this.ul.scrollLeft;
let currentPanel = eval(`this.${name}Panel`); // <-- is this good practice or is there a better way? Removing eval() means `this` is a string and not a reference to the DOM Element that was clicked.
// move the unordered list to the left into the viewport
TweenMax.to(this.ul, 0.75, { scrollTo: { x: currentPanel.getBoundingClientRect().left + currentScrollPosition } });
}
render() {
return (
<section className="video-slider">
<ul ref={ul => this.ul = ul}>
<li ref={ hunterPanel => this.hunterPanel = hunterPanel }>
/* html elements */
</li>
<li ref={ fieldPanel => this.fieldPanel = fieldPanel }>
/* html elements */
</li>
</ul>
<ul>
<li><a onClick={() => this.handlePanelClick(event, "hunter")}><span>Hunter</span></a></li>
<li><a onClick={() => this.handlePanelClick(event, "field")}><span>Field</span></a></li>
</ul>
</section>
);
}
最佳答案
您可以使用Bracket notation []
使用字符串动态定位对象中的属性:
this[`${name}Panel`]
顺便说一下,eval
是邪恶的。尽量不要使用它,除了安全风险之外,浏览器在使用 eval
时会放弃一些优化。
关于javascript - 这是 Javascript 中 eval() 的正确用例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52577597/