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

时间:2018-09-30 11:49:31

标签: 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>
    );
  }

2 个答案:

答案 0 :(得分:5)

您可以使用Bracket notation []动态地将对象指定为带有字符串的对象:

this[`${name}Panel`]

顺便说一句,eval是邪恶的。尝试不要使用它,除了安全隐患之外,浏览器在使用eval时还会进行一些优化。

答案 1 :(得分:-1)

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

重构更多React-ish:

<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
}