How to pass phrases to a variable and then show randomly

1
Well, I started programming yesterday in React Native and I still do not understand very well how to do things .... I need to pass a series of sentences to multiple variables, each variable a phrase, and then present them in a way random.

onPlay(){
      // const um = "testeeeeee";
}

// EVENTS
// SPECIFIC METHODS

render() {   
    return (
      <View style={styles.container}>

        <View style={{flex:1, backgroundColor: 'skyblue'}}>
          <Text style={styles.title}>
            Would You Rather
          </Text>
          <TouchableHighlight style={[styles.primary_button,styles.medium_button]} onPress={this.onPlay.bind(this)}>
          <Text style={styles.medium_button_text}>
            test
          </Text>
          </TouchableHighlight>
        </View>

        <View style={{flex:1, backgroundColor: 'steelblue'}}>
          <TouchableHighlight style={[styles.primary_button,styles.medium_button]} onPress={this.onPlay.bind(this)}>
          <Text style={styles.medium_button_text}>
            test2
          </Text>
          </TouchableHighlight>
        </View>
      </View>
    );
}
    
asked by anonymous 17.05.2017 / 10:37

1 answer

3

You should have these phrases in props or state of the component. That being the case, to avoid duplicating code you can do this:

constructor(props) {
    super(props);
    this.state = {
        frases: [
            {title: 'frase 1', conteudo: 'Olá!'},
            {title: 'frase 2', conteudo: 'Olé!'}
    };
}

// para as misturar aleatoriamente
function misturador() {
    const array = this.state.frases.slice();
    let length = array.length;
    while (counter > 0) {
        let index = Math.floor(Math.random() * counter);
        length--;
        let temp = array[length];
        array[length] = array[index];
        array[index] = temp;
    }
    return array;
}
render() {   
    const frases = this.misturador().map(frase => (
        <View style={{flex:1, backgroundColor: 'skyblue'}}>
          <Text style={styles.title}>{frase.title}</Text>
          <TouchableHighlight style={[styles.primary_button,styles.medium_button]} onPress={this.onPlay.bind(this)}>
          <Text style={styles.medium_button_text}>{frase.conteudo}</Text>
          </TouchableHighlight>
        </View>
    ));
    return (
      <View style={styles.container}>
          {frases}
      </View>
    );
}

Another way, perhaps even better is to have a component for that text and manage within the component as the title is handled. Then you use the same way, with a .map() of the sentence array for the component.

    
17.05.2017 / 11:30