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

Is this a proper usecase for eval() in Javascript?

我经历过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 时放弃了一些优化。

基于 Sagiv 的重构 b.g 接受的答案和 vlaz 建议:

重构了更多 React 风格:

<li><a onClick={() => this.handlePanelClick(event, this.hunterPanel)}><span>Hunter</span></a></li>
          <li><a onClick={() => this.handlePanelClick(event, this.fieldPanel)}><span>Field</span></a></li>

handlePanelClick(event, name) {
event.preventDefault();
const currentScrollPosition = this.ul.scrollLeft;

let currentPanel =  name; // don't do this --> eval(`this.${name}Panel`);
// rest of code
}

重构了更多香草 javascript-ish:

<li><a onClick={() => this.handlePanelClick(event, 'hunter')}><span>Hunter</span></a></li>
          <li><a onClick={() => this.handlePanelClick(event, 'field')}><span>Field</span></a></li>

handlePanelClick(event, name) {
event.preventDefault();
const currentScrollPosition = this.ul.scrollLeft;

let currentPanel =  this[`{name}Panel`]; // don't do this --> eval(`this.${name}Panel`);
// rest of code
}