0

在此示例中,我正在创建一个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,
            },
        ]),
    };
}
4

1 回答 1

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}
        />
    );
};
于 2016-09-27T12:52:58.580 回答