自定义单选按钮 React Native

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


这是我的代码


单选按钮.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>


        );

    }

}

活动日志.js


class ActivityLog extends Component {

    constructor(props){

        super(props); 

    }


哈士奇WWW
浏览 253回答 1
1回答

富国沪深

将activeStatus提取到ActivityLog中来跟踪哪个按钮被选中,现在你为每个按钮维护一个状态作为本地状态。所以很难知道其他组件知道按钮的活动状态。这是一个粗略的想法的通用实现。const Child=(props)=>{&nbsp; &nbsp; <TouchableOpacity onPress={props.handlePress}>&nbsp; &nbsp; &nbsp; &nbsp; <Text style={[baseStyle,active && activeStyle]}>{props.title}</Text>&nbsp; &nbsp; </TouchableOpacity>}class Parent extends React.Component{&nbsp;state={&nbsp; selectedChild:''&nbsp;}&nbsp;changeSelection=(sometitle)=>{&nbsp; this.setState({&nbsp; &nbsp; &nbsp; selectedChild:sometitle&nbsp; })&nbsp;}&nbsp;render(){&nbsp; &nbsp; &nbsp;return(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<View>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Child handlePress={()=>this.changeSelection('1')} active={this.state.selectedChild==='1'}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Child handlePress={()=>this.changeSelection('2')} active={this.state.selectedChild==='2'}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Child handlePress={()=>this.changeSelection('3')} active={this.state.selectedChild==='3'}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Child handlePress={()=>this.changeSelection('4')} active={this.state.selectedChild==='4'}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</View>&nbsp; &nbsp; &nbsp;)&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript