我使用循环创建了按钮的集合。这些按钮的背景颜色一次一个地改变,一个按钮一次。调用该函数时,有什么方法可以获取背景为黑色的按钮的键。
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
selectedControl: 0,
controls: ["TITLE1", "TITLE2", "TITLE3"]
};
}
componentDidMount() {
this.timerHandle = setInterval(() => {
this.setState(({selectedControl, controls}) =>
({selectedControl: (selectedControl + 1) % controls.length})
);
}, 1000);
}
render() {
const {selectedControl, controls} = this.state;
return (
<View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-evenly',
alignItems: 'stretch' }}>
{controls.map((control, index) => (
<Button key={control} title={control} buttonStyle={index === selectedControl ? styles.highlighted : styles.buttonStyle}/>
))}
</View>
);
}
}
const styles = StyleSheet.create({
buttonStyle: {
height: '100%',
},
highlighted: {
height: '100%',
backgroundColor: 'black',
}
});
答案 0 :(得分:1)
按钮键设置为control
。因此,请检查index === selectedControl
中按钮何时突出显示(即render
)并且按钮的键为control
。
<View style={{
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
alignItems: 'stretch'
}}>
{controls.map((control, index) => {
if (index === selectedControl) {
console.log({"key": control}) /* <-- here */
}
return <Button key={control} title={control} buttonStyle={index === selectedControl ? styles.highlighted : styles.buttonStyle}/>
})}
</View>