2017-06-29 9 views
0

私は約2時間を費やしました。本当に助けが必要です。私は私の配列からランダムな色を取得し、その1色にbackgroundColorを設定したいと思います。コードをそこにコピーしました。 https://jsfiddle.net/1x0k2ot4/配列から無作為にbackgroundColorを設定してください

ありがとうございました。

constructor(props) { 
    super(props); 
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 
    this.state = { 
     inputValue: '', 
     backgroundColor: '', 
     dataSource: ds.cloneWithRows([]), 
    }; 
    this._handleTextChange = this._handleTextChange.bind(this); 
    this._handleDeleteButtonPress = this._handleDeleteButtonPress.bind(this); 
    this._setColor = this._setColor.bind(this); 
} 

_setColor() { 
    const backgroundColor = backgroundcolors[Math.floor(Math.random()*backgroundcolors.length)]; 
    this.setState({ 
     backgroundColor: backgroundColor 
    }) 
}<View style={{ backgroundColor: this.state.backgroundColor, alignItems: 'center', height: 80, padding: 8, borderWidth: 1.5, borderColor: '#e0e0e0', flex: 1, flexDirection: 'row', marginBottom: 5,}}> 
           <Text style={styles.todoText}>{rowData}</Text> 
           <View> 
            <TouchableHighlight onPress={handleDelete} style={styles.crossCloseButton}> 
             <View> 
              <Image style={styles.imgClose} source={{uri: 'http://playground.davidfutera.cz/close.png'}}/> 
             </View> 
            </TouchableHighlight> 
           </View> 
          </View> 
+0

あなたが今見ている動作、予想される動作(負荷時などのときのランダムな色)、これまでに試したことを含みます。 –

答えて

1

はこれを試してみてください、それは非常に簡単であるかもしれないあなたの投稿は少し厄介だったが、私は、これはあなたを助けるだろうと思い、何かエラーが教えて得れば、それは

constructor(props) { 
super(props); 
    this.state = { 
    bgColor: [ 
     'red', 
     'blue', 
     'yellow', 
    ], 
    selectedColor: '', 
    }; 
} 


componentDidMount() { 
    this._getRandomColor() 
} 

_getRandomColor(){ 
    var item = this.state.bgColor[Math.floor(Math.random()*this.state.bgColor.length)]; 
    this.setState({ 
    selectedColor: item, 
    }) 
} 

<View style={{backgroundColor: this.state.selectedColor}}> 
    <Text>Test</Text> 
</View> 
+0

うまく動作します、ありがとう:) –

0

を動作するはずですし、あなたが提供した6桁の16進コードジェネレータを使用している場合は、https://www.paulirish.com/2009/random-hex-color-code-snippets/としてください。そうすれば、より無作為でコードはよりエレガントですが、それはずっとランダムです。

関連する問題