1
我有一個水平滾動視圖,裏面添加了裏面有按鈕的子視圖。我想要做的就是突出顯示選中的孩子,並讓其他孩子變暗(基本上更新樣式)。我能夠使用狀態更新選定的孩子的風格,但是如何更新其他的scrollview子元素?我曾嘗試使用裁判,多個州但沒有工作。 任何人都可以請提供一些指針,如何去做呢?在React Native中更新ScrollView中子視圖的樣式
謝謝.. !!
我有一個水平滾動視圖,裏面添加了裏面有按鈕的子視圖。我想要做的就是突出顯示選中的孩子,並讓其他孩子變暗(基本上更新樣式)。我能夠使用狀態更新選定的孩子的風格,但是如何更新其他的scrollview子元素?我曾嘗試使用裁判,多個州但沒有工作。 任何人都可以請提供一些指針,如何去做呢?在React Native中更新ScrollView中子視圖的樣式
謝謝.. !!
您應該讓擁有子視圖的組件負責指定它們是高亮還是灰顯。這樣,選擇哪個孩子應該突出顯示的所有邏輯都位於您的代碼中的一個位置,並且您只需在用戶點擊其中一個孩子時重新渲染所有者組件。
要檢測每個孩子的觸摸事件,請將它們包裝在TouchableWithoutFeedback
組件中。
class OwnerComponent extends React.Component {
state = {
selectedChildIndex: null,
};
render() {
return (
<ScrollView>
<TouchableWithoutFeedback
onPressIn={() => {
this.setState({ selectedChildIndex: 0);
}}
onPressOut={() => {
this.setState({ selectedChildIndex: null);
}}
style={styles.touchableContainer}>
<View style={this.getChildStyle(0)} />
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPressIn={() => {
this.setState({ selectedChildIndex: 1);
}}
onPressOut={() => {
this.setState({ selectedChildIndex: null);
}}
style={styles.touchableContainer}>
<View style={this.getChildStyle(1)} />
</TouchableWithoutFeedback>
</ScrollView>
);
}
getChildStyle(childIndex) {
// No child is selected
if (this.state.selectedChildIndex === null) {
return null;
}
return (this.state.selectedChildIndex === childIndex) ?
styles.highlightedChild :
styles.dimmedChild;
}
}
let styles = StyleSheet.create({
touchableContainer: {
flexGrow: 1,
},
highlightedChild: {
backgroundColor: 0xf0f0f0;
},
dimmedChild: {
opacity: 0.7,
},
});
你可以添加代碼,你怎麼做? –
那麼,你可以讓孩子的selectedId保存狀態,然後讓每個孩子將它自己的ID與selectedId進行比較。如果相同,則需要突出顯示,如果不是,則需要調暗。 只是我頭頂的做法,希望它有幫助! –