亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號