首页 > 解决方案 > 如何从 React Native 中的字符串运行 javascript 逻辑?

问题描述

在我的应用程序中,第三方游戏开发人员将根据我的模板编写简单的 JavaScript 逻辑。他们会将他们的代码输入文本框(在线),我会将他们的代码存储为字符串。

例如,一位游戏开发者会这样写:

const examineItem = (user, item, app) => { //we will pass `user` and `item` with our own methods
    //Developer writes his/her own logic
    if(user.intelligence > 50){
        return({ result: "You see a rock!"});
    }else{
        return({ result: "You see nothing"});
    }
};

在我的 React Native 应用程序中,如何将这个字符串代码“转换”为可运行的函数?我需要翻译吗?我是否使用eval(已弃用)?

我从哪里开始?

标签: javascriptreact-nativecompilationinterpreter

解决方案


其实也不算太难。像这样使用“新函数”运算符:

const examineItem = (user, item, app) => {
  // Developer writes his/her own logic
  const devString = 'return user.intelligence > 50'

  // You can pass as many arguments as you want, just keep the string last:
  const devFunc = new Function('user', 'item', 'app', devString) 

  // Make sure to pass all the arguments to the call:
  if(devFunc(user, item, app)){
    return({ result: "You see a rock!"});
  } else{
    return({ result: "You see nothing"});
  }
};

// Testing it:
const user = { intelligence: 60 }
const res = examineItem(user, null, null)
console.log(res) // { result: "You see a rock!"}

我刚刚测试了这段代码,它应该可以工作。你可以从任何你想要的地方拉出“devString”。

这样做的主要危险只是确保您的所有开发人员都知道哪些参数将传递给他们编写的“字符串”,以及这些参数的数据模型是什么。


推荐阅读