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

React中动态创建script标签并设置data-client-key编译失败求助

Fixing the data-client-key Attribute Issue in Dynamically Created React Script Tags

Hey there! I totally get the frustration when you're trying to add a custom data attribute to a script tag in React and hit a compile error—let's get this sorted out quickly.

The problem you're running into is that trying to assign a data-client-key directly like script.data-client-key = "value" won't work in JavaScript. The hyphen in the attribute name gets misinterpreted as a subtraction operator, which throws a syntax error. Instead, use one of these two standard DOM methods to set the attribute correctly:

Method 1: Use setAttribute()

This is the most straightforward way to add any custom attribute to a DOM element, including data-* attributes:

componentDidMount () {
  const script = document.createElement("script");
  script.src = "https://www.example.com/example.js";
  script.async = true;
  // Add your data attribute here
  script.setAttribute("data-client-key", "your-unique-client-key");
  document.body.appendChild(script);
}

Method 2: Use the dataset Property

DOM elements have a dataset property that maps directly to data-* attributes. For attributes with hyphens, you convert them to camelCase (e.g., data-client-key becomes clientKey in the dataset):

componentDidMount () {
  const script = document.createElement("script");
  script.src = "https://www.example.com/example.js";
  script.async = true;
  // Set via dataset (camelCase for hyphenated attributes)
  script.dataset.clientKey = "your-unique-client-key";
  document.body.appendChild(script);
}

Both of these approaches are valid and will work without triggering React compile errors. They're standard DOM manipulation techniques, which React fully supports in lifecycle methods like componentDidMount.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:21:10