reference 引用
function A (){
return (<h1>组件AAA</h1>)
}
<A ref="comA" /> // 不可这样使用,但是函数组件内部是可以使用ref的
过时方式(不要使用)
以聚焦input事件为例,以前的ref使用方式,ref 值为string已经过时,随时可能被移除(不建议使用,在16版中已不再可用)
export default class RefComp extends React.Component {
render() {
return (
<div>
<input ref="text" type="text" />
<button
onClick={() => {
console.log(this);
this.refs.text.focus()
}}>点击 </button>
</div>
);
}
}
ref值的两种形式
ref 的值根据节点的类型而有所不同:
- 当
ref
属性用于 HTML 元素时,构造函数中使用React.createRef()
创建的ref
接收底层 DOM 元素作为其current
属性。 - 当
ref
属性用于自定义 class 组件时,ref
对象接收组件的挂载实例作为其current
属性。 - 你不能在函数组件上使用 ref 属性,因为他们没有实例。
1.使用React.createRef() 创建( React 16.3 版本引入)
1.1 html 组件
export default class RefComp extends React.Component {
con