【问题标题】:How can i user refs in stateless functions React-Native, am using React-Native 0.62.2我如何在无状态函数 React-Native 中使用 refs,我正在使用 React-Native 0.62.2
【发布时间】:2020-05-01 08:59:25
【问题描述】:

我有一个名为 CodeInput 的输入来自使用 styled/components 的样式,我想从一个地图创建多个输入,但我收到警告功能组件不能被赋予 refs,访问 ref 的尝试将失败。

import React, {useRef} from 'react';

import {CodeInput} from './styles'

const codeInputs = (props) => {
    const inputFields = useRef([])
    const submitClick = index => {
        console.log("ref #: " + inputFields.current);
      };
    return (
        <CodeInput onChange={submitClick} keyboardType="phone-pad" maxLength={1} ref={el => {inputFields[index] = el }} />
    )
}

下面我使用上面的组件来创建多个输入

const renderInputs = () => {
      const array = new Array(4).fill(0)
       return array.map((_, idx)=>(
           <CodeInputs index={idx} key={idx}/>
       ))
 }

【问题讨论】:

  • 改用createRef

标签: javascript react-native


【解决方案1】:

你可以这样使用。

const codeInputs = ({index}) => {
const inputFields = [];
const submitClick = index => {
    console.log("ref #: " + inputFields[index]);
  };
return (
    <CodeInput onChange={() => submitClick(index)} keyboardType="phone-pad" maxLength={1} ref={el => {inputFields[index] = el }} />
)
}

【讨论】:

  • 请在这里分享一个codeandbox链接,这样会更容易理解这个问题。另请确保您已正确检查我的解决方案。我不仅用过数组,很多地方也改了一些小东西
猜你喜欢
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 2022-06-15
  • 2019-06-27
  • 1970-01-01
相关资源
最近更新 更多