2 回答
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
您可以使用回調(diào)參考來(lái)做到這一點(diǎn)。
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 的文檔中閱讀更多相關(guān)信息,盡管其中一些信息比 React 15.5.4 更新(例如React.createRef)。
TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以使用ref, 來(lái)獲取對(duì) 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>;
}
添加回答
舉報(bào)
