在react-native中比较文本

2admgd59  于 2023-05-01  发布在  React
关注(0)|答案(2)|浏览(202)

如何在React Native中比较两个文本对象?
抱歉,如果这个问题太麻烦了。但我花了一个小时调查了所有的可能性,还是找不到正确的答案。

constructor(props) {
super(props)
this.state = { text: ''}
}

render() {
 return (
  <View style={styles.container}>
    <TextInput
      style={styles.inputText}
      onChangeText={this.onChangeDo(this)}
    />
  </View>
 );
}

  onChangeDo(event){
  (text) => this.setState( {text} )
  if(text equals 'string'){
  ...
 }
 else{
 ...
}
xuo3flqw

xuo3flqw1#

好的,你可以检查文本,然后在onChangeText函数中设置变量的状态。Here是一个例子,我也粘贴了下面的代码。
https://rnplay.org/apps/pWvSsg

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  Component
} = React;

class SampleApp extends Component {

  constructor(props) {
    super(props)
    this.state = { text: ''}
  }

  onChangeDo(text) {
    this.setState({ text })
    if (text === 'Hello') {
        return this.setState({ hello: true })
    }
    this.setState({ hello: false })
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
            placeholder="Type Hello"
          style={styles.inputText}
          onChangeText={ (text) => this.onChangeDo(text) }
            />
        { this.state.hello && <Text style={ styles.hello }>Hello World</Text> }
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 60
  },
  inputText: {
    height:60,
    backgroundColor: '#ededed'
  },
  hello: {
    fontSize:22
  }
})

AppRegistry.registerComponent('SampleApp', () => SampleApp);
am46iovg

am46iovg2#

For large Strings Use this approach
    let questions="Hello how are you doing.........................are you fine?............................Whats your full name?.............";
    
    let compareQuestions="Hello how are you doing.........................are you fine?............................Whats your full name?.............";
    
    let comp= Array.from(questions).map((x) => {
            return typeof x === 'string' ? x : '';
          }).join('')==Array.from(compareQuestions).map((x) => {
            return typeof x === 'string' ? x : '';
          }).join('')
console.log("compare============",comp)

相关问题