1

有没有办法重新设置问题或让某个答案将问题引导到另一个先前的问题?

var questions = [{
{
  name: 'morefood',
  message: 'Do you want more food?',
  type: 'list',
  choices: [ 'Yes', 'No'],
},{
  name: 'choiceoffood',
  message: 'Which food do you want more of?',
  type: 'list',
  choices: [ 'Hamburgers', 'Fries', 'Hotdogs']
  when: function(answers) {
    return answers.morefood === 'Yes';
  }
}, {
  name: 'quantityoffood',
  message: 'How much more do you want?',
  type: 'input',
  when: function(answers) {
    return answers.quantityoffood === 'Yes';
  }
},{
  name: 'confirmfood',
  message: 'Do you still want more food?',
  type: 'list',
  choices: [ 'Yes', 'No'],   <=========== if yes then goes back to choiceoffood
}, 
]
4

1 回答 1

1

这似乎有点 hacky,但我相信你必须在你的应用程序逻辑中处理它。例如:

const questionA = {
    type: 'input',
    message: 'Do you like fruit?',
    name: 'questionA',
}

const questionB = {
    type: 'input',
    message: 'What is your favorite fruit?',
    name: 'questionB',
}

const questionC = {
    type: 'input',
    message: 'what is your favorite candy?',
    name: 'questionC',
}

inquirer
    .prompt(questionA)
    .then(answers => {
        if (answers.questionA === 'yes') {
           return inquirer.prompt(questionB)
        } else {
           return inquirer.prompt(questionC)
        }
    })
    .then(answers => {
        if (answers.questionB) {
             return console.log(answers.questionB, 'is a great fruit');
        } 
        if (answers.questionC) {
            return console.log(answers.questionC, 'is a great candy');
        }
    })

更新:

在查看了更多文档之后,似乎“何时”是正确的解决方案。

when: (Function, Boolean) 接收当前用户的答案 hash 并且应该返回 true 或 false 取决于是否应该问这个问题。该值也可以是一个简单的布尔值。

于 2018-05-02T00:36:49.563 回答