react 元素标签组件
JSX is an amazing pseudo-language for React, and if I'm honest, it's what brought me to love React so much. Using React without JSX is cumbersome and frustrating, while using JSX is such an easier way to express your code. One drawback of JSX, however, is that it makes accessing component elements indirect, if not difficult.
JSX是React的一种神奇的伪语言,如果我老实说,这就是让我如此热爱React的原因。 在没有JSX的情况下使用React既麻烦又令人沮丧,而使用JSX则是一种表达代码的简便方法。 但是,JSX的一个缺点是,即使不是很困难,它也会间接访问组件元素。
The truth is that accessing a component's own elements is actually much easier than most think. Let's look at how a component method can access its own DOM node with JavaScript:
事实是,访问组件自己的元素实际上比大多数人想象的要容易得多。 让我们看一下组件方法如何使用JavaScript访问其自己的DOM节点:
方法1:React (Method 1: react-dom)
react-dom provides a findDomNode
method for finding the component's node:
react-dom提供了findDomNode
方法来查找组件的节点:
// Get ReactDOM
import ReactDOM from "react-dom";
// In your component method
class MyComponent extends Component {
myMethod() {
const node = ReactDOM.findDOMNode(this);
}
}
With ReactDOM.findDOMNode(this)
, you can get the widget's main node, and from there you can use typical DOM methods:
使用ReactDOM.findDOMNode(this)
,您可以获得小部件的主节点,然后可以使用典型的DOM方法:
const node = ReactDOM.findDOMNode(this);
// Get child nodes
if (node instanceof HTMLElement) {
const child = node.querySelector('.someClass');
}
This mixes a bit of React and basic JavaScript DOM manipulation.
这混合了一些React和基本JavaScript DOM操作。
方法2: ref
(Method 2: ref
)
Another method of getting DOM nodes is by using ref
s; an example usage is detailed in my React and autofocus post:
获取DOM节点的另一种方法是使用ref
。 我的React和autofocus帖子中详细介绍了一个示例用法:
class MyComponent extends Component {
// The element we want to retrieve
_input: ?HTMLInputElement;
// ....
componentDidUpdate() {
this._input.focus();
}
render() {
return (
<div>
<input
ref={c => (this._input = c)}
/>
</div>
);
}
}
}
Adding a ref
attribute to the element you want a handle on is a more React-centric approach to getting a handle on an element. Both strategies work well so choose whichever you prefer!
向要处理的元素添加ref
属性是一种以React为中心的方法来获取元素的处理。 两种策略都能很好地工作,因此请选择您喜欢的任何一个!
react 元素标签组件