taro 微信小程序 useImperativeHandle 问题



  • 组件代码 components/Demo/index.jsx

    import Taro,{useImperativeHandle} from '@tarojs/taro';
    import {View} from '@tarojs/components';
    
    const Demo = ({childRef}) => {
      useImperativeHandle(childRef, () => ({
        stop () {
          console.log("======")
        }
      }))
      return (
          <View className="demo">111</View>
      )
    }
    
    export default Demo;
    

    页面代码 pages/user.jsx

    import Taro,{useRef} from '@tarojs/taro';
    import {View, Button} from '@tarojs/components';
    import Demo from '../components/Demo';
    
    const User = () => {
      let childRef = useRef();
    
      const handelClick = () => {
        console.log(childRef.current);
        childRef.current.stop()
      }
    
      return(
          <View className="wrap wrap-user">
            <Button onClick={handelClick}>测试</Button>
            <Demo childRef={childRef} />
          </View>
      )
    }
    
    export default User;
    
    

    这样无法在页面上执行到组件中到方法,点击报错。

    b0d15583-2ffa-4c4a-bc18-f3959b83cef5-image.png

    请问这个是我的写法问题还是taro的问题, 使用hooks方式如何在父组件中调用子组件的方法。

    taro info 信息如下

    ➜  MiniApp taro info 
    👽 Taro v2.1.5
    
    
      Taro CLI 2.1.5 environment info:
        System:
          OS: macOS 10.15.4
          Shell: 5.7.1 - /bin/zsh
        Binaries:
          Node: 13.12.0 - ~/.nvm/versions/node/v13.12.0/bin/node
          Yarn: 1.22.4 - ~/.nvm/versions/node/v13.12.0/bin/yarn
          npm: 6.14.4 - ~/.nvm/versions/node/v13.12.0/bin/npm
        npmPackages:
          @tarojs/components: 2.1.5 => 2.1.5 
          @tarojs/components-qa: 2.1.5 => 2.1.5 
          @tarojs/mini-runner: 2.1.5 => 2.1.5 
          @tarojs/mobx: 2.1.5 => 2.1.5 
          @tarojs/mobx-h5: 2.1.5 => 2.1.5 
          @tarojs/router: 2.1.5 => 2.1.5 
          @tarojs/taro: 2.1.5 => 2.1.5 
          @tarojs/taro-alipay: 2.1.5 => 2.1.5 
          @tarojs/taro-h5: 2.1.5 => 2.1.5 
          @tarojs/taro-qq: 2.1.5 => 2.1.5 
          @tarojs/taro-quickapp: 2.1.5 => 2.1.5 
          @tarojs/taro-swan: 2.1.5 => 2.1.5 
          @tarojs/taro-tt: 2.1.5 => 2.1.5 
          @tarojs/taro-weapp: 2.1.5 => 2.1.5 
          @tarojs/webpack-runner: 2.1.5 => 2.1.5 
          eslint-config-taro: 2.1.5 => 2.1.5 
          eslint-plugin-taro: 2.1.5 => 2.1.5 
          nerv-devtools: ^1.5.6 => 1.5.6 
          nervjs: ^1.5.6 => 1.5.6 
          stylelint-config-taro-rn: 2.1.5 => 2.1.5 
          stylelint-taro-rn: 2.1.5 => 2.1.5 
    
    

登录后回复