如何在React Native中创建一个清除按钮

时间:2017-07-30 22:51:29

标签: javascript react-native

我目前正在学习React Native,我正在尝试创建一个清除多个文本输入的清除按钮。我使用以下链接尝试制作清除按钮: https://snack.expo.io/B1xM4CjIb

我合并了这样的例子:

export default class Input extends Component {

    handleLocation = (text) => {
       this.setState({ location: text })
}

    handleStartTime = (text) => {
       this.setState({ startTime: text })
}

    handleEndTime = (text) => {
       this.setState({ endTime: text})
}
    login = (location, startTime, endTime) => {
        alert('Location: ' + location + 'Start Time:' + startTime + 'End Time:' + endTime )
}
    clearInput = () => {
       this.textInputRef.clear();
}

render (){

   return (
   <View style={styles.container}>
       <TouchableOpacity
           style = {styles.submitButton}
           onPress = { () => this.login(this.state.location, this.state.startTime, this.state.endTime)}>
           <Text style = {styles.submitButtonText}>
              Submit
           </Text>
       </TouchableOpacity>
       <Button title= "Clear" onPress={this.clearInput.bind(this)}/>
       <TextInput
           ref={ref => this.textInputRef = ref}/>
           value={this.state.location, this.state.startTime, this.state.endTime}/>
    </View>

当我运行此操作时,我收到错误RawText 'Value=' must be wrapped in an explicit <Text> Component。这只会使单词值出现在屏幕上,而清除按钮仍然不起作用。我该如何解决?感谢任何能提供帮助的人。

3 个答案:

答案 0 :(得分:1)

你可以说

clearInput = () => {
  this.setState({ location: '', startTime: '', endTime: '' });
}

同样,由于此功能是箭头功能。在<Button>我们可以说onPress={this.clearInput},而无需bind(this)

答案 1 :(得分:0)

ref={'whatever'}添加到textInput组件(为每个要清除的文本输入添加一个)

喜欢这个

<TextInput ref={'one'}/>
<TextInput ref={'two'}/>
<TextInput ref={'three'}/>
...

然后使用此功能清除文本:

clearText() {
    this.refs.one.setNativeProps({text: ''});
    this.refs.two.setNativeProps({text: ''});
    this.refs.three.setNativeProps({text: ''});
}

将它附加到buttonPress:

<TouchableOpacity onPress={(text) => this.clearText({text: ''})}/>

答案 2 :(得分:0)

要清除单个输入,可以使用clearButtonMode属性。它会出现在文本视图的右侧。仅单行TextInput组件支持此属性。默认值为“永不”。枚举(“从不”,“边编辑”,“除非编辑”,“始终”)

相关问题