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

问题描述:

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

我成立这样的例子:

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。这只会使字词值出现在屏幕上,而清除按钮仍然不起作用。我该如何解决它?感谢任何能够帮助的人。

+0

TextInput的两个主要属性:'OnTextChanged'和'value'。 '在TextChanged'上随时调用用户添加或删除角色的功能。 'value'是任何时候写在'TextInput'里面的东西。据说,准备好''ref's到你的'TextInput's(其中每个都有'value = {YourValue}'

+0

你能用完整的代码再次详细阐述您的问题? – muhammadaa

+0

你想解决'RawText“值=”必须明确'这个错误被包裹?或者你的代码是不工作的清楚吗? –

你可以只说

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

而且,因为该功能是一个箭头的功能。在<Button>中,我们可以说onPress={this.clearInput},而不需要bind(this)

+0

然后我应该删除这个 this.textInputRef = REF} /> 值= {this.state.location,this.state.startTime,this.state.endTime} /> –

+0

呀裁判将没有目的。此外,溜溜你需要3'',第一个用'value = {this.state.location}',第二个用'value = {this.state.startTime}'&finally'value = {this.state.endTime}'。 – MattyK14

添加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: ''}); 
} 

将其附加到按钮上PressPress:

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