为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

郎朗坤 2022-07-21 22:11:20
目前在我的渲染方法中,我有这样的东西<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 ?如果有人能指出我如何做到这一点的正确方向或一些令人惊叹的文档
查看完整描述

2 回答

?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

您可以使用回调参考来做到这一点。


class MyComponent extends React.Component {

  constructor(props) {

    super(props);


    this.element = null;

    this.setElementRef = (element) => {

      this.element = element;

    };

  }


  componentDidMount() {

    this.element.setAttribute("customattribute", "foo bar");

  }


  render() {

    return (

      <div ref={this.setElementRef} className="classValue">

        Hello world!

      </div>

    );

  }

}

您可以在 React 的文档中阅读更多相关信息,尽管其中一些信息比 React 15.5.4 更新(例如React.createRef)。


查看完整回答
反对 回复 2022-07-21
?
不负相思意

TA贡献1777条经验 获得超10个赞

您可以使用ref, 来获取对 DOM 元素的setAttribute引用componenDidMount:


constructor(props) {

    super(props);

    this.myRef = React.createRef();

}


componentDidMount(){

    this.myRef.current.setAttribute('customAttibute', 'customValue')

}


render() {

    return <h1 ref={this.myRef} className="classValue">This h1</h1>;

}


查看完整回答
反对 回复 2022-07-21
  • 2 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号