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)。

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>;
}
添加回答
舉報