首先,我必须将属性添加到自定义元素/组件,因此我尝试在此处进行操作,但是我只能将其添加到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>
);
}
(根据第一个请求的原始答案)
首先,您必须考虑到传递给自定义组件的每个属性都可以在components上找到props
。
因此,例如,如果在App
名为的组件上传递自定义属性,data-rr-mask
则可以在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
找到您的自定义属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句