React this.refs.dom与ReactDOM.findDOMNode使用与区别

前端之家收集整理的这篇文章主要介绍了React this.refs.dom与ReactDOM.findDOMNode使用与区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、选取 DOM 元素

1.this.refs.name获取dom节点的DOMNode

handleSubmit = () => {
    let name = this.refs.name.value,// 获取DOMnode
        content = this.refs.content.value,publishTime = this.refs.publishTime.value,_test = this._test.value;

        console.log(name,content,publishTime,_test);
}

<div>name: <input type="text" ref="name" /></div>

2.组件的DOMNode只能由ReactDOM.findDOMNode获取

componentDidMount() {
    console.log(this.refs.commnet);    // undefined
    // console.log(this.refs.commnet.offsetWidth);
    console.log(ReactDOM.findDOMNode(this.refs.comment));    //Comment组件的真实dom节点:<div>
    console.log(ReactDOM.findDOMNode(this.refs.comment).offsetWidth);    // 1904
}

<div>
    <CommentList ref="comment" />
</div>

3.React不太推荐或废弃了以上refs的用法,而是用ref callback

_test = this._test;
console.log(_test.value);

<div>test: <input type="text" ref={ test => this._test = test } /></div>
原文链接:https://www.f2er.com/react/303474.html

猜你在找的React相关文章