我向我的每个列表项目添加了一个自定义单选按钮。因此,每个项目行的左侧都有一个单选按钮,我希望能够根据行项目在单选按钮的选定值之间进行切换。因此,我可以选择第一个行项目并选择/切换为选中状态,或者选择第二个行项目将其切换为打开状态,而将第一行项目关闭。
我对如何为当前对象设置逻辑有些困惑。我当前的对象有一个ID和isSelected布尔值。布尔值将指示该行是否为isSelected(即已选中)。
这是我到目前为止的内容:
这是我的组件,用于呈现平面列表fooItems。 fooItems本身是组成列表的各个元素。
export class FooItemsComponent extends Component {
constructor(props) {
super(props);
}
async componentDidMount() {
//some reducer action
}
renderItem = item => {
if (item.load) {
return <ActivityIndicator color={Colors.activityColor} size="small" />;
} else {
return (
<View>
<FooItem
{...item}
navigation={this.props.navigation}
showParticularItems={true}
/>
</View>
); }
};
render() {
const { fooItems, navigation, loading, props} = this.props;
if (!fooItems) fooItems = [];
return (
<View style={styles.container}>
<FlatList
keyExtractor={(item, index) => `key-${index}`}
data={fooItems}
renderItem={item => this.renderItem(fooItems.item)}
ItemSeparatorComponent={Separator}
ListHeaderComponent={Header}
ListFooterComponent={loading ? LoadingFooter : Separator}
/>
</View>
);
}
}
FooItem组件:
export default class FooItem extends Component {
constructor(props) {
super(props);
this.state = {
isSelected: this.props.fooItems.isSelected
};
}
changeSelected = isSelected => {
if(!isSelected) {
let selected = this.props.fooItems;
selected = selected.isSelected = true;
this.setState({ isSelected: selected});
}
};
render() {
const {
Details,
showPreferred = false,
showSetSelected = false,
navigation
} = this.props;
const { isSelected} = this.state;
return (
<View
style={[ showSetSelected? styles.setDefaultContainer :
styles.container,
showBorder ? { borderBottomWidth: 1, borderTopWidth: 1 } : {},
]}
>
{showSetSelected && (
<View>
<TouchableOpacity
style={[styles.info, !isSelected ? styles.lineBreak : {}]}
onPress={() => this.changeSelected(isSelected)}
>
<RadioButton isChecked={isSelected}></CheckedCircle>
</TouchableOpacity>
</View>
)}
</View>
);
}
}
我的自定义控件:
const RadioButton = ({ isChecked }) => {
let checkedStatus;
switch (isChecked) {
case true:
checkedStatus = <Image style={styles.container} source={require('../../../assets/radioButton.png')} />
break
default:
checkedStatus = <Image style={styles.container} source={require('../../../assets/circle.png')} />
break
}
return <View style={styles.container}>{checkedStatus}</View>
}
[现在,我注意到尚未选择的另一行,并且选择了它,选中了该特定行的单选按钮状态,但是现在我有两个已选中/选定的行,而不是一个。所以我想知道如何切换另一行。我该怎么做?
您需要跟踪在FooItem
状态下选择了哪个FooItemsComponent
。然后用它来检查
<FooItem
{...item}
isSelected={this.state.selectedItem.id === item.id}
navigation={this.props.navigation}
showParticularItems={true}
/>
或某种方式。