小程序ref
大家好,我是小阵 🔥,一路奔波不停的码字业务员
身为一个前端小菜鸟,总是有一个飞高飞远的梦想,因此,每点小成长,我都想要让它变得更有意义,为了自己,也为了更多值得的人
如果喜欢我的文章,可以关注 ➕ 点赞,与我一同成长吧~😋
加我微信:zzz886885,邀你进群,一起学习交流,摸鱼学习两不误🌟
ref代码
constructor(){
// 如果用的是Taro的话,可以使用Taro.createRef()
this.myRef = React.createRef();
this.myRefminiapp = React.createRef();
this.myRefs = React.createRef();
this.myRefsminiapp = React.createRef();
this.state = {
myRef2 : null,
myRef2miniapp : null,
myRefs2 : null,
myRefs2miniapp : null,
}
}
render(){
console.log('ref print:',this.myRef,this.refs.refstring,this.state.myRef2)
return (
<View>
{/* Ref */}
{/* 自定义组件 Ref React.createRef() 类型 */}
<FloatPanel
ref={this.myRef}
/>
{/* 自定义组件 Ref string 类型 */}
<FloatPanel
ref='refstring'
/>
{/* 自定义组件 Ref Function 类型 */}
<FloatPanel ref={newref => {
this.setState({ myRef2: newref })
}} />
{/* 原生小程序组件 Ref React.createRef() 类型 */}
<View
ref={this.myRefminiapp}
/>
{/* 原生小程序组件 Ref string 类型 */}
<View
ref='refstringminiapp'
/>
{/* 原生小程序组件 Ref Function 类型 */}
<View ref={newref => {
this.setState({ myRef2miniapp: newref })
}} />
{/* Refs */}
{/* 自定义组件 Refs React.createRef() 类型 */}
<FloatPanel
refs={this.myRefs}
/>
{/* 自定义组件 Refs string 类型 */}
<FloatPanel
refs='refsstring'
/>
{/* 自定义组件 Refs Function 类型 */}
<FloatPanel refs={newref => {
this.setState({ myRefs2: newref })
}} />
{/* 原生小程序组件 Refs React.createRef() 类型 */}
<View
refs={this.myRefsminiapp}
/>
{/* 原生小程序组件 Refs string 类型 */}
<View
refs='refsstringminiapp'
/>
{/* 原生小程序组件 Refs Function 类型 */}
<View refs={newref => {
this.setState({ myRefs2miniapp: newref })
}} />
</View>
)
}
ref总结
| ref 属性 | 自定义组件 | 原生元素(比如:View) |
| ---------------------- | --------------------- | -------------------- | |
| Ref string | this.refs返回React组件本身 | 返回Fs |
|Ref React.createRef() | 返回{current:react组件本身} | 返回{current:Fs} |
| Ref Function | 返回React组件本身 | 返回Fs |
| refs Function | 编译报错 | 编译报错 |
| refs React.createRef() | {current:null} | 返回{current:Fs} |
| refs string | undefined | this.refs返回空对象 |
Fs:
Fs._component就是当前View所在的页面或组件实例
如果自己测试的ref情况跟上述总结不对,需要考虑下是否是赋值、渲染与打印顺序的问题