猿问

在 React v15.5.4 中将自定义属性设置为 DOM 元素

目前在我的渲染方法中,我有这样的东西

<h1 customAttibute="customValue" className="classValue">This h1</h1>

这是在我的浏览器中呈现的

<h1 class="classValue">This h1</h1>

这是因为 React 15 似乎不支持自定义属性

令人讨厌的是,在 React v16 中,这个问题似乎已经解决,但在这个阶段升级到 React 16 对我来说不是一个选择 - https://reactjs.org/blog/2017/09/08/dom-attributes-in-react- 16.html

无论如何我可以为我的元素添加一个自定义属性,也许是 setAttribute ?如果有人能指出我如何做到这一点的正确方向或一些令人惊叹的文档


郎朗坤
浏览 238回答 2
2回答

侃侃尔雅

您可以使用回调参考来做到这一点。class MyComponent extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.element = null;&nbsp; &nbsp; this.setElementRef = (element) => {&nbsp; &nbsp; &nbsp; this.element = element;&nbsp; &nbsp; };&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.element.setAttribute("customattribute", "foo bar");&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div ref={this.setElementRef} className="classValue">&nbsp; &nbsp; &nbsp; &nbsp; Hello world!&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}您可以在 React 的文档中阅读更多相关信息,尽管其中一些信息比 React 15.5.4 更新(例如React.createRef)。

不负相思意

您可以使用ref, 来获取对 DOM 元素的setAttribute引用componenDidMount:constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.myRef = React.createRef();}componentDidMount(){&nbsp; &nbsp; this.myRef.current.setAttribute('customAttibute', 'customValue')}render() {&nbsp; &nbsp; return <h1 ref={this.myRef} className="classValue">This h1</h1>;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答