在 React (v15) 的 render() 中访问 DOM

Access DOM in render() of React (v15)

在学习React的过程中,发现了如下代码

据我了解,React 中的 DOM 通常通过 Refs.

访问

但是,这段代码使用了document,我还没有看到任何人使用这种方式。

我是不是理解错了?这是正式的方式吗?

另外,document.form 等同于 document.getElementByTagName("form")?

任何参考都会有所帮助。

    export default class IssueAdd extends React.Component {
    constructor() {
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e) {
        e.preventDefault();
        const form = document.forms.issueAdd;
        this.props.createIssue({
            owner: form.owner.value,
            title: form.title.value,
            status: 'New',
            created: new Date(),
        });
        form.owner.value = '';
        form.title.value = '';
    }

    render() {
        return (
            <div>
                <form name="issueAdd" onSubmit={this.handleSubmit}>
                    <input type="text" name="owner" placeholder="Owner" />
                    <input type="text" name="title" placeholder="Title" />
                    <button>Add</button>
                </form>
            </div>
        );
    }
}

在 React 中不推荐通过文档变量访问 DOM。

如您所说,您应该为您的元素创建一个引用并通过它访问它。 (更多关于参考文献:https://reactjs.org/docs/refs-and-the-dom.html


简短示例:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  getOffset = () => {
    console.log(this.myRef.current.offsetTop); // will output the offset top of the div
  }

  render() {
    return <div ref={this.myRef} onClick={this.getOffset}>Test div</div>;
  }
}

这将在点击时控制台记录 div 的偏移量顶部。


信息:React.createRef() 是在 React 16.3 中添加的,在此之前你有回调 Refs——更多关于它的信息在文档中...

React 只是另一个 javascript 库,因此它具有您可能在普通 javascript 中使用的所有功能,例如访问 window 对象或 document 对象。 但这是否意味着你应该使用它们,绝对不和 you will find the reasons here。直接 DOM 操作是非常昂贵的操作。

基本上,React 的工作原理是 virtual DOM。 Virtual DOM 使 React 更新实际 DOM 变得 更容易和更快 ,而无需超过多个直接 DOM 操作的开销。

来到 refs,因为我们不想使用 document 对象访问 HTML 元素 React 提供了 Refs,这将有助于进入特定元素并快速访问它(它将 return 来自虚拟 DOM 的数据)。

几篇关于参考文献的好文章:

偏离路线

BTW: Welcome to the wonderful world of React :)