【发布时间】:2020-03-04 17:05:45
【问题描述】:
我为每个平面列表项添加了一个自定义单选按钮。因此,每个项目行的左侧都有一个单选按钮,我希望能够根据行项目在单选按钮的选定值之间切换。因此,我可以选择第一行项目并且选择/切换或选择第二个项目并且切换并且第一行项目被切换。
我对如何用我当前的对象设置这个逻辑有点困惑。我当前的对象有一个 id 和 isSelected bool。 bool 将指示该行是否为 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>
}
现在,我注意到另一行尚未选中,我选择了它,该特定行的单选按钮状态已选中,但现在我有两个选中/选中的行而不是一个。所以我想知道如何切换另一行。我怎样才能完成这项工作?
编辑:
列表中的单选按钮切换示例,我只想在列表行之间列出的单选按钮之间切换。
【问题讨论】:
-
能否分享一下问题的截图,有助于更好地理解问题。
-
问题现在是我点击的任何单选按钮被选中,当它应该切换时。预期的行为在上面的示例图片中。 @bk7
标签: javascript reactjs react-native