我们将无法通过单击来触发 的onFocus事件侦听器。然而,我们可以通过一些巧妙的 CSS 让它看起来像正在发生的事情。TextInputText
- 确保 的背景
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