我如何在无状态函数React-Native中使用用户引用,正在使用React-Native 0.62.2

问题描述 投票:0回答:1

我从使用styled/components的样式中获得了一个名为CodeInput的输入,我想从一个映射创建多个输入,但收到警告,无法为ref提供功能组件,尝试访问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}/>
       ))
 }
javascript react-native
1个回答
0
投票
您可以这样使用。

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 }} /> ) }

© www.soinside.com 2019 - 2024. All rights reserved.