【问题标题】:How to get ref x, y position in functional component in react-native?如何在 react-native 中获取功能组件中的 ref x、y 位置?
【发布时间】:2021-06-01 13:18:22
【问题描述】:

当文本光标聚焦在 TextInput 上时,我想获取 x、y 位置。

如何获得参考位置?

这是我的代码

const Code = () => {
  const emailInput = useRef();
  const scrollViewRef = useRef();

  const [email, setEmail] = useState<string>('');


  const scrollToEmail = () => {
// I want to scroll the y position of the scroll to the center where the TextInput's cursor is focused.
  };

  return (
    <SafeAreaView style={{ flex: 1}}>
      <ScrollView keyboardShouldPersistTaps="handled" ref ={scrollViewRef}>
        <KeyboardAvoidingView enabled behavior={'padding'}>
     
          <TextInput
            ref={emailInput}
            value={email}
            returnKeyType="done"
            onChangeText={(text) => setEmail(text)}
            onFocus = {() => scrollToEmail()} <== function works here!
          />

        </KeyboardAvoidingView>
      </ScrollView>

    </SafeAreaView>
  );
};

export default Code;

我试过了

1.

const handler = findNodeHandle(emailInput.current); 
  console.log(
    emailInput.measure(handler, (x, y, width, height) => {
      console.log(y);
    }),
    ); <== TypeError: emailInput.measure is not a function 
const handler = findNodeHandle(emailInput.current); 
  console.log(emailInput.current.getBoundingClientRect()); <== TypeError: emailInput.current.getBoundingClientRect is not a function 

没有办法在功能组件中获取 ref 的位置吗?

【问题讨论】:

    标签: scrollview react-functional-component use-ref react-native-textinput


    【解决方案1】:

    你可以在ScrollView上使用onLayout prop来获取高度、宽度、X和Y值。

    如果您想使用ref,您必须在useLayoutEffect 上设置或控制台记录X 和Y 值。这是因为在获取信息之前需要等待组件渲染和“绘制”,否则只会得到 0

    【讨论】:

    • 我尝试了 onLayout 但是,onLayout 捕获了父组件的 x,y。如果你有两个 TextInputs,onLayout 不是很有帮助。
    猜你喜欢
    • 2017-05-01
    • 2021-05-18
    • 2021-09-15
    • 2021-09-11
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多