我们将无法通过单击来触发 的onFocus
事件侦听器。然而,我们可以通过一些巧妙的 CSS 让它看起来像正在发生的事情。TextInput
Text
- 确保 的背景
TextInput
是透明的或至少与Text
. 当我们给予时,这种方式Text
仍然可见position: absolute
。然后我们
- 我们需要
zIndex
的Text
低于zIndex
的
TextInput
。那个方式TextInput
其实就是在Text前面。因此,虽然看起来您正在单击placeholder
,但实际上您只是在单击 ,TextInput
这将触发onFocus
事件。
尝试这个:
import React, { Component } from "react";
import { StyleSheet, Text, TextInput } from "react-native";
class App extends Component {
state = {
active: false,
text: ""
};
activeField = () => {
console.log("focused");
this.setState({
active: true
});
};
handleOnBlur = () => {
if (this.state.text.length === 0) {
this.setState({
active: false
});
}
};
render() {
return (
<div>
{!this.state.active && (
<Text style={STYLES.textInputPlaceholder}>
{this.props.placeholder}
</Text>
)}
<TextInput
style={STYLES.textInputField}
onChangeText={text => this.setState({ text })}
onFocus={this.activeField}
value={this.state.text}
onBlur={this.handleOnBlur}
/>
</div>
);
}
}
const STYLES = StyleSheet.create({
app: {
marginHorizontal: "auto"
},
textInputField: {
zIndex: 1,
width: 300,
borderColor: "black",
borderWidth: 1
},
textInputPlaceholder: {
zIndex: -1,
color: "blue",
position: "absolute",
backgroundColor: "transparent"
}
});
export default App;
App.defaultProps = {
placeholder: "Hello"
};
这是工作沙箱:https ://codesandbox.io/s/react-native-on23p