前言
本文通过四种方式来告诉你如何使用,虽然有一种被放弃了。今日早读文章由老虎集团@joking_zhang翻译授权分享。
正文从这开始~~
使用 React 时,我们的默认思维方式应该是 不会强制修改 DOM ,而是通过传入 props 重新渲染组件。但是,有些情况却无法避免修改 DOM 。
React 中的 Refs 提供了一种访问 render() 方法中创建的 React 元素(或 DOM 节点)的方法。
当父组件需要与子组件交互时,我们通常使用 props 来传递相关信息。 但是,在某些情况下,我们可能需要修改子项,而不用新的props 重新呈现 (re-rendering) 它。 这时候就需要 refs 出场了。
我什么时候应该使用 Refs ?
我们建议在以下情况下使用 refs:
与第三方 DOM 库集成
触发命令式动画
管理焦点,文本选择或媒体播放
译注:第三点是否也可以理解为使用 event 对象呢?在 React 中就是合成事件(SyntheticEvent)。
官方文档中提到:避免使用 refs 来做任何可以通过声明式实现来完成的事情。
所以一旦我们确定我们真的应该使用 refs,我们需要如何使用它们呢?
在 React 中使用 Refs
您可以通过多种方式使用 refs :
React.createRef()
回调引用 (Callback refs)
String refs(已过时)
转发 refs (Forwarding refs)
接下来,让我们看看每一种实现方式:
React.createRef()
可以使用该 React.createRef() 函数创建 Refs ,并通过该 ref 属性附加到 React 组件中的 HTML 元素。
通常在组件的构造函数内创建 ref ,使其在整个组件中可用。例如:
class MyComponent extends React.Component {
constructor(props) {
super(props);this.firstRef = React.createRef();}
render() {
return <div ref={
this.firstRef} />;}}
如上所示:
一个 ref 实例在构造函数中创建,并赋值给 this.firstRef
在 render() 方法内部,将构造函数中创建的 ref 传递给 div
接下来,让我们看一个在 React 组件中使用 refs 的示例。
使用 Refs 聚焦输入
这是另一个例子:
// Ref.jsclass CustomTextInput extends React.Component {
constructor(props) {
super(props);// create a ref to store the textInput DOM elementthis.textInput = React.createRef();this.focusTextInput = this.focusTextInput.bind(this);}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API// Note: we're accessing "current" to get the DOM nodethis.textInput.current.focus();}
render() {
// tell React that we want to associate the ref// with the `textInput` that we created in the constructorreturn (
<input type="text" ref={
this.textInput} /><input
type="button"
value="Focus the text input"
onClick={
this.focusTextInput}/>div>);}}
在上面的代码块中,我们构建了一个按钮,当单击它时,该页面会自动聚焦在输入框上。
首先,我们在构造方法中创建一个 ref 实例,并将其赋值给 this.textInput,然后通过 ref 属性将其分配给 input 元素。
type="text" ref={this.textInput} />
注意,当 ref 属性被一个 HTML 元素使用时(比如当前示例中的 input 元素),在 constructor 中使用 React.createRef() 创建的 ref 会接收来自底层 DOM 元素的 current 值。
译注:这里的 current 应该是 合成事件(SyntheticEvent)