怎么学习和了解一个技术点
他源自哪里?
- 比如 ref 属性,我们应该明确他是来自 react 的一个属性
他是什么?
- 定义是什么?具体的属性是什么?
- 比如 react 的 ref 属性,当我们需要在典型数据流之外强制的修改一个子组件的时候。
- 要修改的子组件可以是 react 组件实例,也可以是 DOM 元素。对于这种情况下,react 提供了一个 ref 属性。
怎么用?
- React提供可以附加到任何组件的特殊属性。 ref属性接受一个回调函数,回调函数将在组件被挂载或卸载后立即执行。
import React from 'react';
import ReactDOM from 'react-dom';
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="选中上面的text input" onClick={this.focus}/>
</div>
);
}
}
ReactDOM.render(
<CustomTextInput/>,
document.getElementById('root')
);
什么时候用?(使用场景)
- 通过ref属性设置回调函数
- 当在自定义组件上使用ref属性时,ref回调接收组件的已装入的组件实例作为其参数。 例如,如果我们想要包装上面的CustomTextInput来模拟它在装载(mounting)后立即被点击:
class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
}
render() {
return (
<CustomTextInput ref={input => {this.textInput = input; }} />
);
}
}