在一般的数据流中也就是从上而下的单向数据流中,我们一般都是父组件要影响控制子组件必须要通过props 来处理,即便是之前讲过this.state ,但是那个东西也是针对自己的,而不是增对其它组件的,组件之间的影响到目前为止只能通过props 来处理,这会非常的麻烦,所以React 提供了一个特殊的接口来处理这种事件。
ref 的用处
ref 用在处理表单空间聚焦,文本选择,媒体播放以及触发动画效果等等
官方强调不要用ref 直接去做非常明显的事件,比如说Dialog 组件打开和关闭的open() 和close() 可以通过isOpen 去控制,而不是明显的函数处理
ref 是一个React 的非常特殊的属性,这个属性一定是接受一个回调函数,这个回调函数会在组件渲染时进行执行一遍,在从视图中撤出来时会执行一遍
1.为DOM 元素增加ref
当我们用为HTML 元素增加ref 属性时,我们的ref 会传递一个参数给回调函数
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
this.textInput.focus();
}
render() {
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
当React 在组件渲染时调用回调函数时,这个参数就是DOM 元素本身,在撤离视图时会返回null
2.为类组件增加ref
跟HTML 元素一样,为类组件调用ref 回调函数的时机是一样的,只是参数是组件的一个实例
class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
}
render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}
3.ref 在函数式组件中不可用
不要企图在函数式组件中使用ref 属性来进行回调函数的绑定,因为函数式组件是没有实例的,准确的说函数式组件不是一个真正的类
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} />
);
}
}
就前面一篇博客提到的,我们应该将函数式组件转换为类组件,才能使用ref 属性,当然虽然无法对函数式组件使用ref 属性,但是为函数式组件里面的HTML 元素和类组件使用ref 属性是可以的
function CustomTextInput(props) {
let textInput = null;
function handleClick() {
textInput.focus();
}
return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
不要过度的使用ref 属性
ref 从一定程度上增加了组件之间的耦合性,导致难以分离,所以如果可以用props 来处理的事情,尽量不要用ref 来处理
过时的refs 字符串
在以前的一些React 版本通过this.refs 可以获取一个字符串,这个方法在将来会被抛弃所以请不要使用,即便是ref 可以设置为一个字符串,但是强烈建议用回调函数
下一篇将讲React 中的非控制型组件
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|