【问题标题】:React native multiple ref to global component将本机多个 ref 反应到全局组件
【发布时间】:2021-01-23 05:47:36
【问题描述】:

我想为同一个全局组件创建多个引用。例如 TextInput ,如果我想向它添加 ref 我使用。这在我的基于类的组件中:

 <TextInput
               
                  ref={input => {
                    this.secondTextInput = input;
                  }}
                
                />

然后通过this.secondTextInput.focus(); 调用以聚焦文本输入。只要我将整个 textInput 直接导入我的班级,它就可以工作。

如果我在另一个文件中为 TextInput 创建了一个全局组件,例如:

export const OTPInput = props => {
  return (
    
      <TextInput
        placeholder={props.title}
        onChangeText={props.onTextEnter}
        value={props.value}
      
      />
   
  );
};

并在我的课程中使用它,方法是像这样导入:

Class ABC extends Component{


render(){
return(
<>
<OTPInput title ="first otp" />
<OTPInput title ="another otp" />
</>
)

}

}

如何创建 ref 并传递它,以便我可以通过单击类 func 中的某个按钮来聚焦文本输入。

任何帮助都会很棒

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    Forwarding Refs

    export const OTPInput = React.forwardRef((props, ref) => (
      <TextInput
        ref={ref}
        placeholder={props.title}
        onChangeText={props.onTextEnter}
        value={props.value}  
      />
    ));
    

    然后根据您的示例用法,只需创建一个 ref 并附加

    const OTPInputRef1 = React.createRef();
    
    ...
    
    <OTPInput ref={OTPInputRef1} title ="first otp" />
    

    【讨论】:

    • 哦,好吧,如何聚焦文本字段? OTPInputRef1.focus() 可以吗?
    • @GauravRoy 啊,是的,如果您使用的是旧样式Callback Refs,但如果使用当前的accessing react refs 方法,则更可能是OTPInputRef1.current.focus()
    • 非常感谢,它现在确实很专注。太棒了:D,只是一个疑问,我的文本输入已经填充了 redux 值,但是当它聚焦时它失去了分配给它的值。有点古玩
    【解决方案2】:

    你应该看看反应文档中描述的转发引用 https://reactjs.org/docs/forwarding-refs.html

    【讨论】:

      猜你喜欢
      • 2019-03-23
      • 2018-12-02
      • 1970-01-01
      • 2017-10-02
      • 2020-04-10
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多