[英]How to add data attribute to HTML element in JSX without any value
起初我不得不向自定義元素/組件添加一個屬性,所以我在這里嘗試這樣做,但我只能將它添加到非自定義元素,如 div 和 input。
https://codesandbox.io/s/react-16-966eq
const dAttribute = { "data-rr-mask": "" };
const App = () => (
<div style={styles}>
<h4>Context </h4>
<FeatureContext {...dAttribute} name="Context" />
<hr />
<h4> Error2 Boundaries</h4>
<FeatureErrorBoundaries />
<hr />
<h4> Fragment</h4>
<h2>
<FeatureFragment />
</h2>
<hr />
<h4>Reference</h4>
<FeatureRef />
<hr />
<h4>Portals</h4>
<FeaturePortal />
<hr />
<h4>Life Cycle</h4>
<FeatureLifeCycle />
</div>
);
render(<App {...dAttribute} />, document.getElementById("root"));
此外,此屬性最終將用於 HTML 元素,我需要它沒有任何值,例如: <input data-rr-mask />
另一個問題是我必須添加一個空字符串作為值; 否則,應用程序會拋出錯誤。
有沒有辦法做到這一點,這樣你就不會在元素內得到"data-rr-mask"=''
編輯(基於評論,OP 實際上是在生成的 HTML 上尋找要解析的數據屬性,沒有任何值)
為了完全消除生成的 HTML 元素的值,正如用戶對我的回答所評論的那樣,您只需要為您的數據屬性/道具使用一個空字符串。
export default function App() {
return (
<div className="App">
<input data-rr-mask="" /> {/* will be resolved to <input data-rr-mask> on the generated HTML code*/}
</div>
);
}
(基於第一個請求的原始答案)
首先,您必須考慮傳遞給自定義組件的每個屬性,然后都可以在組件props
上找到。
因此,例如,如果您在名為data-rr-mask
App
組件上傳遞自定義屬性,則可以在App
的道具下找到它:
const App = (props) => {
console.log(props) // { "data-rr-mask": "foo" }
return <div>
<MySecondCustomComponent {...props} />
</div>
};
render(<App data-rr-mask="foo" />, document.getElementById("root"));
然后,在你的MySecondCustomComponent
的props
你可以找到你的自定義屬性。
在我的理解中,一個沒有值的道具是一個值為真的布爾道具。
所以這意味着
<div someProp />
是相同的
<div someProp={true} />
嘗試以下操作是否能解決您的問題:
const dAttribute = { "data-rr-mask": true };
有關布爾 HTML 屬性的更多信息,請參閱https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.