繁体   English   中英

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

[英]How can i user refs in stateless functions React-Native, am using React-Native 0.62.2

我使用styled/components从 styles 有一个名为 CodeInput 的输入,我想从 map 创建多个输入,但我收到警告无法为功能组件提供参考,尝试访问参考将失败。

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

你可以这样使用。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM