You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Inquirer v6的后续问询中使用前置答案生成验证摘要?

在Inquirer v6中引用前置答案并生成验证摘要

当然可以!在Inquirer v6里,你完全能在后续的问询中调用之前收集到的答案,实现方式非常直观——只需要把配置项里的message设置成一个函数就行。这个函数会自动接收之前的answers对象作为参数,你可以直接从中提取需要的内容来生成动态提示。

先纠正你示例代码里的小语法错误:你最后一行的字符串拼接多了一个闭合单引号,而且直接写answers.name会报错,因为在普通字符串字面量里无法直接访问变量,用函数返回模板字符串会更清晰易读。

下面是修正后的基础示例:

this.prompt([
  {
    type: 'input',
    name: 'name',
    message: 'What is your name?',
    default: 'Jake'
  },
  {
    type: 'confirm',
    name: 'summary',
    // 用函数返回动态提示,接收answers参数
    message: (answers) => `Is this information correct? Your name is: ${answers.name}`
  }
])

如果需要生成包含多个前置答案的完整摘要,只需要在message函数里把所有需要展示的字段拼接起来就行,比如添加年龄、邮箱等信息后:

this.prompt([
  {
    type: 'input',
    name: 'name',
    message: 'What is your name?',
    default: 'Jake'
  },
  {
    type: 'input',
    name: 'age',
    message: 'How old are you?'
  },
  {
    type: 'input',
    name: 'email',
    message: 'What is your email?'
  },
  {
    type: 'confirm',
    name: 'verifyAll',
    message: (answers) => 
      `Please confirm your details:\n- Name: ${answers.name}\n- Age: ${answers.age}\n- Email: ${answers.email}\n\nIs all this information correct?`
  }
])

另外补充个小技巧:除了message,Inquirer的很多配置项(比如when控制是否显示当前问询、default设置默认值)都支持传入函数并接收answers参数,能帮你实现更灵活的动态问询逻辑。

内容的提问来源于stack exchange,提问作者Ari Shaposhnik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:31:26