从数组设置随机背景颜色

Dav*_*era 2 react-native

我在这上面花了大约 2 个小时,我真的需要帮助。我想从我的数组中获取随机颜色,然后将 backgroundColor of 设置为一种颜色。我在那里复制了我的代码。https://jsfiddle.net/1x0k2ot4/

谢谢你的每一个建议。

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>
Run Code Online (Sandbox Code Playgroud)

Bru*_*ine 6

试试这个,你的帖子有点乱,但我认为这会帮助你,如果出现错误告诉我,它应该可以工作

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>
Run Code Online (Sandbox Code Playgroud)