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://segmentfault.com/a/1190000010255722
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞