Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

hook中如何获取子组件实例

在React Native里需要用到select组件,自己开发了一个,但是碰到了拿不到子组件实例的尴尬。
原来在class组件里可以通过ref很方便的拿到子组件实例,但是在useRef里只能拿到子组件的方法,拿不到组件实例,但是在当前组件里又可以取到某个元素的实例。

import 'react-native-gesture-handler';
import React, {useEffect, useRef} from 'react';
import {View, Text} from 'react-native';
import {Select, Option, OptionList, updatePosition} from './src/Dropdown';

function App() {
  const selectRef = useRef(null);
  const optionlistRef = useRef(null);
  const testRef = useRef(null)
  useEffect(() => {
    // updatePosition(selectRef.current);
    //updatePosition(testRef.current);
    console.log(子组件实例',optionlistRef)
  }, []);
  getOptionList = () => {
    return optionlistRef;
  };

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <View style={{width: '100%',height: 50,borderWidth: 2,borderColor: 'black'}} ref={testRef}>
        <Select
          width={250}
          ref={selectRef}
          optionListRef={getOptionList()}
          defaultValue="请选择"
          onSelect={(val) => console.log('我选择了哪个省了', val)}>
          <Option>Alberta</Option>
          <Option>British Columbia</Option>
          <Option>Manitoba</Option>
          <Option>New Brunswick</Option>
          <Option>Newfoundland and Labrador</Option>
          <Option>Northwest Territories</Option>
          <Option>Nova Scotia</Option>
          <Option>Nunavut</Option>
          <Option>Ontario</Option>
          <Option>Prince Edward Island</Option>
          <Option>Quebec</Option>
          <Option>Saskatchewan</Option>
          <Option>Yukon</Option>
        </Select>
        <OptionList ref={optionlistRef} />
      </View>
    </View>
  );
}

export default App;

上面的testRef输出结果可以获取到当前组件里的实例
image.png
optionListRef的输出结果可以拿到组件的两个方法,但是拿不到组件实例
image.png

React Native里有个方法 ReactNative.findNodeHandle(ref)需要传递组件实例,这个有没有办法解决呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以使用 useImperativeHandle + forwardRef 包装 OptionList 向上暴露 OptionList 组件实例.

但是你这里设计是不是有点怪怪的。
OptionList 应该是 Select 组件的下拉选项吧?为什么不直接以props方式向 Select 传入选项dataList,或者将 OptionList 以 props 方式传入?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...