ref的3种用法:
在 React v16.3 之前,ref 通过字符串(string ref)或者回调函数(callback ref)的形式进行获取。
- ref 通过字符获取:
// string ref
class MyComponent extends React.Component {
componentDidMount() {
this.refs.myRef.focus();
}
render() {
return <input ref="myRef" />;
}
}
- ref 通过回调函数获取:
// callback ref
class MyComponent extends React.Component {
componentDidMount() {
this.myRef.focus();
}
render() {
return <input ref={(ele) => {
this.myRef = ele;
}} />;
}
}
在 v16.3 中,经 0017-new-create-ref 提案引入了新的 API:React.createRef。
- ref 通过 React.createRef 获取:
// React.createRef
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
this.myRef.current.focus();
}
render() {
return <input ref={this.myRef} />;
}
}
参考链接:
能力上最好的方法是用回调函数
JS与jQuery对象之间的转换
1、js对象转换成jquery对象。 $(js对象);
2、jquery对象转换成js对象。 (1)jquery对象[索引值] (2)jquery对象.get(索引值)