您的位置:首页 > Web前端 > React

React学习之进阶ref的必要性(十三)

2017-03-19 11:37 399 查看
在一般的数据流中也就是从上而下的单向数据流中,我们一般都是父组件要影响控制子组件必须要通过
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
中的非控制型组件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: