背景颜色不重新渲染

时间:2016-09-27 10:02:40

标签: reactjs react-native state background-color react-native-listview

在此示例中,我创建了一个ListView,其中包含一组TouchableOpacity按钮。其中只有一个应该用蓝色突出显示。

确定背景颜色的表达式:

backgroundColor:rowData.key==this.state.selected?'blue':'transparent'

问题在于backgroundColor不会改变,尽管调用render()方法并且状态正在更新。

我甚至试过forceUpdate(),在这种情况下,它渲染了两次,但没有更新颜色。

渲染方法:

render() {
    console.log("RE-RENDER",this.state.selected);//GETS CALLED, STATE UPDATED
    return (
        <ListView
            dataSource={this.state.dataSource}
            keyboardShouldPersistTaps={true}
            renderRow={(rowData) =>
                rowData.visible &&
                    <TouchableOpacity
                        style={{backgroundColor:rowData.key==this.state.selected?'blue':'transparent'}}
                        onPress={(evt) => {
                            this.setState({
                                selected:rowData.key,
                            }, function() {
                                console.log("NEW",this.state.selected);
                                this.forceUpdate();//DOESN'T HELP
                            });
                        }}
                    >
                        <Text>{rowData.value}</Text>
                    </TouchableOpacity>
                }
            automaticallyAdjustContentInsets={false}
        />
    );
};

构造

constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
        dataSource: ds.cloneWithRows([
            {
                key: 'first',
                value: 'BMW',
                visible: true,
            },{
                key: 'second',
                value: 'Mercedes',
                visible: true,
            },
        ]),
    };
}

1 个答案:

答案 0 :(得分:0)

问题是ListView没有重新渲染,因为DataSource did not change。通过添加key属性,每次外部密钥更新时都会触发更新。

render() {
    console.log("RE-RENDER",this.state.selected);//GETS CALLED, STATE UPDATED
    return (
        <ListView
            key={this.state.selected} // SOLVED MY PROBLEM
            dataSource={this.state.dataSource}
            keyboardShouldPersistTaps={true}
            renderRow={(rowData) =>
                rowData.visible &&
                    <TouchableOpacity
                        style={{backgroundColor:rowData.key==this.state.selected?'blue':'transparent'}}
                        onPress={(evt) => {
                            this.setState({
                                selected:rowData.key,
                            }, function() {
                                console.log("NEW",this.state.selected);
                                this.forceUpdate();//DOESN'T HELP
                            });
                        }}
                    >
                        <Text>{rowData.value}</Text>
                    </TouchableOpacity>
                }
            automaticallyAdjustContentInsets={false}
        />
    );
};