如何在JSX中使用模板字面量?含data-slick属性动态传参场景
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.autoplayis a boolean value (true/false), not a string like"true"—invalid JSON will break Slick's configuration. - If
props.numberorprops.breakpointcome in as strings, convert them to numbers first (e.g.,${Number(props.number)}) to avoid string values in the JSON.
2. JSON Stringify (Recommended)
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

