javascript - 这是 Javascript 中 eval() 的正确用例吗?

标签 javascript reactjs eval

我已经浏览过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/

相关文章:

javascript - 如何隐藏 Jquery 中已使用 .load 函数加载的元素

html - 如何将 react 应用程序导出为纯静态 html

PHP 函数和变量以字符串形式存储在数据库中

javascript - Froala 编辑器无法使用

javascript - 将变量从一个函数传递到另一个函数

javascript - 将 blob 直接上传到 s3 时出现问题

reactjs - react : stuck at wait-on at localhost:3000

javascript - JS减少问题

javascript - Java:从 ScriptEngine javascript 返回一个对象

python3/hy - 评估 python 中的 hy 表达式?