本文来自#React系列教程:https://mp.weixin.qq.com/mp/appmsgalbum?__biz=Mzg5MDAzNzkwNA==&action=getalbum&album_id=1566025152667107329)
在React的开发模式中,通常情况下不需要、也不建议直接操作DOM原生,但是某些特殊的情况,确实需要获取到DOM进行某些操作:
如何创建refs
来获取对应的DOM呢?目前有三种方式:
this.refs.传入的字符串
格式获取对应的元素;React.createRef()
方式创建出来的;current
属性就是对应的元素;代码演练:
import React, { PureComponent, createRef } from 'react'
export default class App extends PureComponent {
constructor(props) {
super(props);
this.titleRef = createRef();
this.titleEl = null;
}
render() {
return (
<div>
<h2 ref="title">String Ref</h2>
<h2 ref={this.titleRef}>Hello Create Ref</h2>
<h2 ref={element => this.titleEl = element}>Callback Ref</h2>
<button onClick={e => this.changeText()}>改变文本</button>
</div>
)
}
changeText() {
this.refs.title.innerHTML = "你好啊,李银河";
this.titleRef.current.innerHTML = "你好啊,李银河";
this.titleEl.innerHTML = "你好啊,李银河";
}
}
ref
的值根据节点的类型而有所不同:
ref
属性用于 HTML 元素时,构造函数中使用 React.createRef()
创建的 ref
接收底层 DOM 元素作为其 current
属性;ref
属性用于自定义 class
组件时,ref
对象接收组件的挂载实例作为其 current
属性;ref
属性,因为他们没有实例;这里我们演示一下ref
引用一个class
组件对象:
import React, { PureComponent, createRef } from 'react';
class Counter extends PureComponent {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
render() {
return (
<div>
<h2>当前计数: {this.state.counter}</h2>
<button onClick={e => this.increment()}>+1</button>
</div>
)
}
increment() {
this.setState({
counter: this.state.counter + 1
})
}
}
export default class App extends PureComponent {
constructor(props) {
super(props);
this.counterRef = createRef();
}
render() {
return (
<div>
<Counter ref={this.counterRef}/>
<button onClick={e => this.increment()}>app +1</button>
</div>
)
}
increment() {
this.counterRef.current.increment();
}
}
函数式组件是没有实例的,所以无法通过ref
获取他们的实例:
React.forwardRef
,后面我们也会学习 hooks
中如何使用ref
;import React, { PureComponent, createRef } from 'react';
function Home(props) {
return (
<div>
<h2 ref={props.ref}>Home</h2>
<button>按钮</button>
</div>
)
}
export default class App extends PureComponent {
constructor(props) {
super(props);
this.homeTitleRef = createRef();
}
render() {
return (
<div>
<Home ref={this.homeTitleRef}/>
<button onClick={e => this.printInfo()}>打印ref</button>
</div>
)
}
printInfo() {
console.log(this.homeTitleRef);
}
}
使用forwardRef
import React, { PureComponent, createRef, forwardRef } from 'react';
const Home = forwardRef(function(props, ref) {
return (
<div>
<h2 ref={ref}>Home</h2>
<button>按钮</button>
</div>
)
})
export default class App extends PureComponent {
constructor(props) {
super(props);
this.homeTitleRef = createRef();
}
render() {
return (
<div>
<Home ref={this.homeTitleRef}/>
<button onClick={e => this.printInfo()}>打印ref</button>
</div>
)
}
printInfo() {
console.log(this.homeTitleRef.current);
}
}
在React中,HTML表单的处理方式和普通的DOM元素不太一样:表单元素通常会保存在一些内部的state
。
比如下面的HTML表单元素:
<form>
<label>
名字:
<input type="text" name="name" />
label>
<input type="submit" value="提交" />
form>
在 HTML 中,表单元素(如、