【问题标题】:How to Focus on TextInput on click of button in react native如何在 React Native 中单击按钮时专注于 TextInput
【发布时间】:2021-11-13 00:18:54
【问题描述】:

当我单击编辑按钮时,我试图将焦点设置在 TextInput 上,但出现错误。

下面是我的代码:

const MyProfileScreen = (props: any) => {
    const refsFocus = useRef(null);
    return (
        <>
            <View>
                <TextInput
                    placeholder={'editable test'}
                    placeholderTextColor={'red'}
                    style={{color: 'red'}}
                    ref={refsFocus}
                />
            </View>
            <TouchableOpacity
                onPress={()=> { refsFocus.current.focus();} }
                >
                <Text>Edit text input</Text>
            </TouchableOpacity>
        </>
    );
};

但我在onPress={()=&gt; { refsFocus.current.focus()} } 上遇到错误

错误信息:

Object is possibly 'null'

const refsFocus: React.MutableRefObject&lt;null&gt;

我无法弄清楚我做错了什么

【问题讨论】:

    标签: typescript react-native react-hooks react-native-android react-native-ios


    【解决方案1】:

    您应该像这样将 useRef 挂钩分配给 Textinput ref

    ref={refsFocus}
    

    然后在 onPress 方法中你应该这样调用它

    onPress={()=> { refsFocus.current.focus()} }
    

    同时从 onPress 箭头函数中删除分号。

    【讨论】:

    • Object is possibly 'null',在 refsFocus.current 上收到此错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多