React native 反应本机单选卡列表/单选按钮

React native 反应本机单选卡列表/单选按钮,react-native,React Native,我是个新手,所以我非常感谢你的帮助 我正在尝试创建一个类似单选按钮的卡片列表: 列表中的项/卡是自定义的本地组件 一次只能选择一张卡 应用于卡的样式取决于是否选中该卡 应该可以检查当前选择的卡 请注意,由于公司的限制,我必须使用自定义组件来实现这一点,并且不能使用已经制作好的UI工具包,如Native Base或React Native元素 下面是我做的一个快速可视化示例的屏幕截图 请注意,在上面的屏幕截图中,只有两张卡,但是列表中可能有更多的卡 以下是我迄今为止为自定义卡组件编写的代码:

我是个新手,所以我非常感谢你的帮助

我正在尝试创建一个类似单选按钮的卡片列表:

  • 列表中的项/卡是自定义的本地组件
  • 一次只能选择一张卡
  • 应用于卡的样式取决于是否选中该卡
  • 应该可以检查当前选择的卡
请注意,由于公司的限制,我必须使用自定义组件来实现这一点,并且不能使用已经制作好的UI工具包,如Native Base或React Native元素

下面是我做的一个快速可视化示例的屏幕截图

请注意,在上面的屏幕截图中,只有两张卡,但是列表中可能有更多的卡

以下是我迄今为止为自定义卡组件编写的代码:

// Card.js
export default class Card extends React.Component {
  render() {
    return (
      <TouchableOpacity style={cardStyles.cardContainer}>
        {this.props.children}
      </TouchableOpacity>
    );
  }
}

const cardStyles = StyleSheet.create({
  cardContainer: {
    height: 300,
    width: 300,
    backgroundColor: "#1AAA8E",
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginHorizontal: 5,
    shadowColor: "rgba(0,0,0, .4)",
    shadowOffset: { height: 1, width: 1 },
    shadowOpacity: 1,
    shadowRadius: 1,
    elevation: 5
  }
//Card.js
导出默认类别卡扩展React.Component{
render(){
返回(
{this.props.children}
);
}
}
const cardStyles=StyleSheet.create({
卡片容器:{
身高:300,
宽度:300,
背景色:“1AAA8E”,
边界半径:10,
辩护内容:“中心”,
对齐项目:“中心”,
marginHorizontal:5,
阴影颜色:“rgba(0,0,0,4)”,
阴影偏移:{高度:1,宽度:1},
阴影不透明度:1,
阴影半径:1,
立面图:5
}
我使用的组件如下所示:

render() {
  return (
    <View style={styles.spaceAroundCenter}>
      <Text style={styles.titleText}>Single Select Cardlist</Text>
      <View>   <--- This View should hold the list of cards
          <Card>
            <Text style={{ color: "#fff", fontSize: 30, fontWeight: "bold" }}>
              SELECTED
            </Text>
          </Card>
          <Card2>
            <Text style={{ color: "#000", fontSize: 20, fontWeight: "bold" }}>
              NOT SELECTED
            </Text>
          </Card2>
        </View>
    </View>
  );
}

render(){
返回(
单选卡片列表

在这种情况下,您应该考虑使用ListLIST,并且只在其上传递数组,所选的应该存储在状态中,以跟踪选择哪一个。

/**主要组件*/
状态={
选中:空,
数据:[“选定”、“未选定”]
}
render(){
返回(
单选卡片列表
项目}
extraData={this.state.selected}
renderItem={({item)=>{
返回(
this.setState({selected:item})
选定项={this.state.selected===item}
>
{item}
)
}}
/>
);
}
/**卡片组件*/
导出默认类别卡扩展React.Component{
render(){
const{selected,onPress}=this.props
返回(
{this.props.children}
);
}
}
const cardStyles=StyleSheet.create({
卡片容器:{
身高:300,
宽度:300,
背景颜色:“fff”,
边界半径:10,
辩护内容:“中心”,
对齐项目:“中心”,
marginHorizontal:5,
阴影颜色:“rgba(0,0,0,4)”,
阴影偏移:{高度:1,宽度:1},
阴影不透明度:1,
阴影半径:1,
立面图:5
}