0

Just trying to get my head around styled-components, specifically the suggestion in the docs which says you can set up media query templates like this:

const breakpoint = (...args) => {

    return css`
        @media (min-width: 600px) {
            ${css(...args)}
        }
    `
}

That works fine and can easily be used like this:

${media`background: dodgerblue;`}

I want to create a bunch of media templates but the docs suggest creating named ones which could be used like this:

${media.large`background: dodgerblue;`}

I would prefer to pass an additional parameter to my function though to change the breakpoint, rather than create a different function for each one (not least because I want to be able to have an arbitrary number of them and call them by integer rather than a name). I tried just passing an argument to the template literal like this:

const breakpoint = (bp, ...args) => {

    const minWidth = arrayOfBreakpoints(bp);

    return css`
        @media (min-width: ${minWidth}px) {
            ${css(...args)}
        }
    `

}

$breakpoint(1)`background: olive;`
$breakpoint(2)`background: blue;`

This obviously doesn't work and I have no idea how to pass an additional parameter to the function which the tagged template literal uses as I obviously don't understand how they work. Any ideas?

4

1 回答 1

0

您可能正在寻找一个咖喱函数:

const breakpoint = (bp) => {
    const minWidth = arrayOfBreakpoints(bp);
    return (...args) => {
        return css`
            @media (min-width: ${minWidth}px) {
                ${css(...args)}
            }
       `;
    };
}

$breakpoint(1)`background: olive;`
$breakpoint(2)`background: blue;`
于 2019-02-05T22:00:26.657 回答