繁体   English   中英

自定义单选按钮 React Native

[英]Custom Radio Button React Native

嘿,所以我是新来反应原生和 javascript,目前我正在学习制作一个带有图像的自定义单选按钮,看起来像这样在此页面中的自定义单选按钮用户将从列表中选择一个按钮,我想要在页面第一次渲染时显示一个按下的按钮,并且用户只能选择一个按钮。 谁能告诉我如何解决这个问题? 提前致谢

这是我的代码

RadioButton.js

 export default class RadioButton extends Component { constructor(props) { super(props); this.state = { selected: this.props.currentSelection === this.props.value, } } button() { var imgSource = this.state.selected? this.props.normalImg: this.props.selectedImg; return ( <Image source={ imgSource } /> ); } render() { let activeButton = this.props.activeStyle? this.props.activeStyle: styles.activeButton; return ( <View style={[styles.container, this.props.containerStyle, this.state.selected || this.props.normalImg? activeButton: inactiveButton]}> <TouchableOpacity onPress={() => { this.setState({ selected: .this.state;selected }). }}> { this;button() } </TouchableOpacity> </View> ); } }

ActivityLog.js

 class ActivityLog extends Component { constructor(props){ super(props); } render() { return ( <View style={styles.innerContainer}> <Text style={styles.dialogText}>{`Log my activity at ${time} as...`}</Text> <View style={styles.buttonContainer}> <RadioButton selectedImg={img.activity.breakA} normalImg={img.activity.break} containerStyle={{marginHorizontal: normalize(10)}}/> <RadioButton selectedImg={img.activity.meetingA} normalImg={img.activity.meeting} containerStyle={{marginHorizontal: normalize(10)}}/> </View> <View style={styles.buttonContainer}> <RadioButton selectedImg={img.activity.otwA} normalImg={img.activity.otw} containerStyle={{marginHorizontal: normalize(10)}}/> <RadioButton selectedImg={img.activity.officeA} normalImg={img.activity.office} containerStyle={{marginHorizontal: normalize(10)}}/> </View> ); } }

将 activeStatus 提取到 ActivityLog 以跟踪选择了哪个按钮,现在您为每个按钮维护一个 state 作为本地 state。因此很难知道其他组件来了解按钮的活动状态。

这是粗略想法的通用实现。

const Child=(props)=>{
    <TouchableOpacity onPress={props.handlePress}>
        <Text style={[baseStyle,active && activeStyle]}>{props.title}</Text>
    </TouchableOpacity>
}
class Parent extends React.Component{
 state={
  selectedChild:''
 }
 changeSelection=(sometitle)=>{
  this.setState({
      selectedChild:sometitle
  })
 }
 render(){
     return(
         <View>
             <Child handlePress={()=>this.changeSelection('1')} active={this.state.selectedChild==='1'}/>
             <Child handlePress={()=>this.changeSelection('2')} active={this.state.selectedChild==='2'}/>
             <Child handlePress={()=>this.changeSelection('3')} active={this.state.selectedChild==='3'}/>
             <Child handlePress={()=>this.changeSelection('4')} active={this.state.selectedChild==='4'}/>
         </View>
     )
 }
}

Expo 演示链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM