【发布时间】:2022-06-28 00:44:56
【问题描述】:
【问题讨论】:
-
像reactnative.dev/docs/textinput#onblur这样的道具很多。您可以使用这些事件句柄来更新状态或其他任何内容。
标签: reactjs react-native
【问题讨论】:
标签: reactjs react-native
要使用这些命令式方法,请将组件实例存储在 React ref 中。
const UselessTextInput = () => {
const textInputRef = React.useRef(null); // new
const [text, onChangeText] = React.useState("Useless Text");
const [focused, setFocused] = React.useState(null);
return (
<SafeAreaView>
<TextInput
ref={textInputRef}
style={styles.input}
onChangeText={onChangeText}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
value={text}
/>
{/* New */}
<TouchableOpacity onPress={() => textInputRef.current?.focus()}>
<Text>Focus text input</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
您可以在"Refs and the DOM" section of the React docs 中阅读更多相关信息。
【讨论】:
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
} from "react-native";
import React, { useRef, useState } from "react";
export default function App(props) {
const textInputRef = useRef(null);
const [text, setText] = useState("Useless Text");
const [focused, setFocused] = useState(null);
return (
<View style={styles.container}>
<TextInput
ref={textInputRef}
style={styles.input}
onChangeText={setText}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
value={text}
/>
<TouchableOpacity
style={styles.button}
onPress={() => textInputRef.current.clear()}
>
<Text>Clear text input</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
button: {
backgroundColor: "dodgerblue",
margin: 50,
padding: 20,
borderRadius: 20,
},
input: {
backgroundColor: "green",
height: 100,
width: 300,
borderRadius: 25,
textAlign: "center",
},
});
我终于用了这个,仅供其他用户参考。
【讨论】:
更新:
您应该使用以下方式为输入文本字段分配引用:
const textInputRef = useRef(null);
...
<TextInput
ref={(input) => { textInputRef.current = input; }}
placeholder="Text Input"
/>
并使用这个 ref 来触发 .focus 等事件。
例如
<Button
label="Focus on Input"
onClick={() => { this.textInputRef.current.focus(); }}
/>
更多详情可以参考下面的回答here
旧答案(根据我对问题的理解):
您可以使用类似的道具轻松使用这些事件(基于您正在使用的组件)
例如,对于文本输入
import React from "react";
import { SafeAreaView, StyleSheet, TextInput } from "react-native";
const UselessTextInput = () => {
const [text, onChangeText] = React.useState("Useless Text");
const [focused, setFocused] = React.useState(null);
return (
<SafeAreaView>
<TextInput
style={styles.input}
onChangeText={onChangeText}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
value={text}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
},
});
export default UselessTextInput;
【讨论】:
.current 中,而不是直接存储在变量中。