简体   繁体   English

JavaScript-使用.map时将第二个参数传递给ES6模板

[英]JavaScript - Pass second argument to ES6 Template whilst using .map

I am using es6 templates but have run into an issue when trying to pass a second argument to another template used internally within the original. 我正在使用es6模板,但是在尝试将第二个参数传递给原始内部使用的另一个模板时遇到问题。

At first I was only using a result.relevantJobTypes argument but now I am trying to also pass the result.id for use within the template but I'm not sure how to do it because of the map . 最初,我只使用result.relevantJobTypes参数,但是现在我试图也将result.id传递给模板使用,但是由于map原因,我不确定该怎么做。

var resultTemplate = ({ result }) => {
    return `
        ${result.id} 
        ${result.relevantJobTypes.length < 1 ? '' : `
            ${result.relevantJobTypes.map(jobType => jobTypeTemplate({
                jobType // , result.id -> I want to use result.id somehow in jobTypeTemplate
            })).join('')}
        `}
    `;
}

var jobTypeTemplate = ({ jobType }) => {
    // template code
}

Update 更新

Trying to implement @Bergi's answer but the id is undefined within the relevantJobTypes template: 试图实现@ BERGI的答案,但该ID是内未定义relevantJobTypes模板:

${result.relevantJobTypes.length < 1 ? '' : `
    ${result.relevantJobTypes.map(jobType => jobTypeTemplate({
        jobType
    }, result.id)).join('')}
`}

var jobTypeTemplate = ({ jobType, id }) => {
    // template code
}

#2 #2

Finally got it, I had to update the signature of jobTypeTemplate to be var jobTypeTemplate = ({ jobType }, id) => { rather than jobType, id 终于明白了,我不得不将jobTypeTemplate的签名更新为var jobTypeTemplate = ({ jobType }, id) => {而不是jobType, id

It's just a standard function call, this has nothing to do with template literals. 这只是一个标准函数调用,与模板文字无关。 Instead of 代替

jobTypeTemplate({
    jobType, result.id // SyntaxError
})

you will need to use 您将需要使用

jobTypeTemplate({
    jobType
}, result.id)

for a second argument. 第二个论点。 Of course you could also put a second property in the object literal: 当然,您也可以在对象文字中添加第二个属性:

jobTypeTemplate({
    jobType,
    id: result.id
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM