ref使用_react_vue

99 阅读1分钟

1_react中使用

1_1 同页面使用

    import { useRef } from 'react'
    import { Input, Button } from 'antd'
    import styles from './index.less'

    const HomePage = () => {
      const inputRef = useRef(null)
      const handleClick = () => {
      //点击按钮后会触发input聚焦
        inputRef.current.focus()
      }
      return (
        <div className={styles.homePage}>
          首页
          <Input ref={inputRef} type='text'></Input>
          <Button onClick={handleClick}>点击</Button>
        </div>
      )
    }
    export default HomePage

1_2 父子组件中使用

父组件
    import { useRef } from 'react'
    import { Input, Button } from 'antd'
    import styles from './index.less'
    import Child from './child'
    
    const HomePage = () => {
      const inputRef = useRef(null)
      const childRef = useRef(null)
      const handleClick = () => {
        inputRef.current.focus()
        childRef.current.update()
      }
      return (
        <div className={styles.homePage}>
          首页
          <Input ref={inputRef} type='text'></Input>
          <Button onClick={handleClick}>点击</Button>
          <Child ref={childRef}></Child>
        </div>
      )
    }
    export default HomePage

子组件
    import React, { useImperativeHandle, forwardRef } from 'react'
    import { Button } from 'antd'
    import styles from './index.less'

    const Child = forwardRef((props, ref) => {

      useImperativeHandle(ref, () => ({
        update: () => {
          console.log('---')
        }
      }))
      return (
        <div className={styles.homePage}>
          子页面
        </div>
      )
    })
    export default Child

注意点:一个ref只能绑定一个dom元素,子组件参数必须加上props

2_vue中使用_触发弹窗是否打开

父组件

    <template>
      <div id="epidemicSituation">
        <div class="baseBox">
          <DialogMessage :dialogData="dialogData" ref="dialog"/>
        </div>
      </div>
    </template>
    <script>
    import DialogMessage from './dialog.vue'
    export default {
      components: { DialogMessage },
      data() {
        return {
            dialogData: ''
        }
      },
      methods: {
      this.$ref.dialog.open()
      }
    }
    </script>

子组件

    <template>
      <van-dialog
        v-model="show"
        title="提示"
        :message="dialogData"
        width="205px"
        confirmButtonColor="#3595FB"
      />
    </template>
    <script>
    export default {
      props: {
        dialogData: {
          type: String,
          default: ''
        }
      },
      data() {
        return { show: false }
      },
      methods: {
        open() {
          this.show = true
        }
      }
    }
    </script>