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

如何在JSX中使用模板字面量?含data-slick属性动态传参场景

Using Dynamic Props in JSX for data-slick Attribute

Got it, let's tackle how to convert that static data-slick attribute into a dynamic one using props in JSX. Here are two solid approaches, with the second being my recommended go-to:

1. Direct Template Literal Approach

You can use ES6 template literals to swap static values with your props directly in the attribute string. Just remember to use backticks for the template string, and keep your JSON syntax valid (stick with double quotes for JSON keys, no quotes around boolean values):

<section className="slider" 
  data-slick={`{"slidesToShow": ${props.number},"autoplay": ${props.autoplay}, "responsive": [{"breakpoint":${props.breakpoint},"settings":{"slidesToShow": 2}}]}`}
>
  {/* Your slider content goes here */}
</section>

Quick Notes:

  • Ensure props.autoplay is a boolean value (true/false), not a string like "true"—invalid JSON will break Slick's configuration.
  • If props.number or props.breakpoint come in as strings, convert them to numbers first (e.g., ${Number(props.number)}) to avoid string values in the JSON.

This method is cleaner, more maintainable, and far less prone to syntax errors. First build a JavaScript object with your dynamic props, then convert it to a valid JSON string using JSON.stringify():

// Define your dynamic Slick config first
const slickConfig = {
  slidesToShow: props.number,
  autoplay: props.autoplay,
  responsive: [
    {
      breakpoint: props.breakpoint,
      settings: {
        slidesToShow: 2 // Swap with props.mobileSlidesToShow if this needs to be dynamic too
      }
    }
  ]
};

// Pass the stringified config to data-slick
<section className="slider" data-slick={JSON.stringify(slickConfig)}>
  {/* Your slider content goes here */}
</section>

Why this is better:

  • The config structure is clear and easy to modify—no digging through a long template string to make changes.
  • JSON.stringify() automatically handles valid JSON formatting, including escaping special characters if needed.
  • No juggling quotes or worrying about typos breaking your Slick setup.

Critical Reminder:

Don’t forget to replace class with className in JSX—class is a reserved keyword in JavaScript, so JSX uses className for HTML class attributes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:19:05