Example
示例1
简单的用法就是丢一个TextInput到应用里,然后订阅它的onChangeText事件来读取用户的输入。注意,从TextInput里取值这就是目前唯一的做法!也就是使用在onChangeText中用setState把用户的输入写入到state中,然后在需要取值的地方从this.state中取出值。它还有一些其它的事件,譬如onSubmitEditing和onFocus。一个简单的例子如下
import React, { Component } from 'react';
import { TextInput,StyleSheet } from 'react-native';
export class pageComponent extends Component {
constructor(props) {
super(props);
this.state = { text: 'Useless Placeholder' };
}
render() {
return (
<TextInput
style={styles.textInput}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
);
}
}
const styles = StyleSheet.create({
textInput: {
height: 40,
borderColor: 'gray',
borderWidth: 1
},
});
它的两个方法.focus()和.blur(),它们分别是使TextInput获取和失去焦点。
示例2
注意有些属性仅在multiline为true或者为false的时候有效。此外,当multiline=false时,为元素的某一个边添加边框样式(例如:borderBottomColor,borderLeftWidth等)将不会生效。为了能够实现效果你可以使用一个View来包裹TextInput:
import React, { Component } from 'react';
import {View,TextInput,StyleSheet } from 'react-native';
class UselessTextInput extends Component {
render() {
return (
<TextInput
{...this.props} // 将父组件传递来的所有props传递给TextInput;比如下面的multiline和numberOfLines
editable = {true}
maxLength = {40}
/>
);
}
}
export class pageComponent extends Component {
constructor(props) {
super(props);
this.state = {
text: 'Useless Multiline Placeholder',
};
}
// 你可以试着输入一种颜色,比如red,那么这个red就会作用到View的背景色样式上
render() {
let viewStyle={
backgroundColor: this.state.text,
borderBottomColor: '#000000',
borderBottomWidth: 1,
marginTop:100
}
return (
<View style={viewStyle}>
<UselessTextInput
multiline = {true}
numberOfLines = {4}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
</View>
);
}
}