【问题标题】:Having trouble with multiple active states in ReactJS在 ReactJS 中遇到多个活动状态的问题
【发布时间】:2018-12-10 16:24:00
【问题描述】:

stackOverflowers 同胞周一快乐!我只想知道是否有任何方法可以在单击时保持活动状态彼此独立。我似乎无法弄清楚如何使它们彼此独立。我有状态作为切换。默认情况下,每个按钮的活动状态为 false。单击时,它将状态切换为相反。问题是当单击其中一个按钮并切换状态时,其他按钮的状态也是如此。代码见下:

    import React, {Component} from "react";
import { Button, Progress } from 'reactstrap';
import "../src/Questions.css";


const items = [
    {
        question:"Category",
        buttonList: [
            'Games',
            "Business",
            'Education',
            'Lifestyle',
            "Entertainment",
            "Utility",
            "Social",
            "Other"
        ],
        multiple: false,
        answers: [],

    },
    {
        question:"Platform",
        buttonList: [
            'Android',
            'iOS',
            'Both'
        ],
        multiple: false,
        answers: [],

    },
    {
        question:"Design Type",
        buttonList: [
            'Barebones',
            'Stock',
            'Custom'
        ],
        multiple: false,
        answers: [],

    },
    {
        question:"Development Type",
        buttonList: [
            'Native',
            'Web',
            'Hybrid'
        ],
        multiple: false,
        answers: [],

    },
    {
        question:"Does the app connect to a server",
        buttonList: [
            'Yes',
            'No'

        ],
        multiple: false,
        answers: [],

    },
    {
        question:"Does the app require users to sign in",
        buttonList: [
            'Yes',
            'No'

        ],
        multiple: false,
        answers: [],

    },
    {
        question:"Additional Features",
        buttonList: [
            'Audio',
            'Camera',
            '3rd party API',
            "Dashboard",
            "Social login",
            "Task list",
            "Search",
            "Rating system",
            "Chat",
            "Privacy Settings",
            "Gallery",
            "QR code",
            "Calendar",
            "Social sharing",
            "Activity feed",
            "Push notifications",
            "Ads",
            "Multilangual",
            "Feedback",
            "Data collection",
            "Geo location",
            "Office capabilities",
            "Activity tracking",
            "Augmented reality",
            "Virtual reality",
            "Data export",
            "Maps",
            "Backup"
        ],
        multiple: true,
        answers: [],

    },
    {
        question:"Last Step",
        buttonList: [
            'Games3',
            'Business3',
            'Education3'
        ],
        multiple: false,
        answers: [],

    },
];

function checkElementIsSelected(array, element) {
    if (array.length === 0) {
        return false;
    }

    return(array.find(item => {
        return item === element;
    }));
}

class Questions extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
        value:0,
        count:0,
        display: items[0]['question'],
        active:false

    }};

 handleClickNext = (e) => {
     e.preventDefault();
     this.setState({
         value:this.state.value +10,
         count: this.state.count + 1,
         display: items[this.state.count]['question'],
         email: ''
     })

     console.log('+++', this.state.count);
 }

handleClickAnswer = (e) => {
    e.preventDefault();

    const question = this.state.count;
    if (!items[this.state.count].multiple) {
        items[this.state.count].answers = [e.target.value];
    } else {
        if (!checkElementIsSelected (items[this.state.count].answers, e.target.value)) {
            items[this.state.count].answers.push(e.target.value);
        }
    }
    console.log('--- answers: ', items[this.state.count].answers);

        this.setState({
            active:!this.state.active
        })
        console.log("True or False Active",this.state.active );

}


handleSubmit = (e) => {
    e.preventDefault();
    this.props.history.push("/Success");
    console.log('***', items);
}

handleEmail = (e) => {
    e.preventDefault();

    items[items.length - 1].answers = [e.target.value];
    console.log("$$$Emails: '", items[items.length - 1].answers);

}


render() {
    let element;
    let next;

    if (this.state.count === items.length) {
        element = <input type="text" onChange={this.handleEmail}/>
        next = <Button color='primary' onClick={this.handleSubmit}>Get my estimate</Button>

    } else {
        element = items[this.state.count].buttonList.map(btn => {
            return (
                <div>
                    <Button outline color="primary" value={btn} onClick={this.handleClickAnswer} active={this.state.active}>{btn}</Button>
                </div>
            )
        });

        next = <Button onClick={this.handleClickNext} color="primary" size="lg" value='Next'>Next</Button>;
    }


    return(
        <div>
            <div><Progress value={this.state.count * (100 / items.length)} /></div>
            <div className="howMuchText">How much does it cost to build an app</div>
            <div className="questionTitle">{this.state.display}</div>
            <div className="buttonChoices">
                {
                    element
                }
            </div>

            <div className="nextButton">
                {next}
            </div>
        </div>
    )
 }
}

  export default Questions;

非常感谢任何帮助。谢谢!!!!

【问题讨论】:

  • 代码 sn-p 看起来不完整。什么是checkElementIsSelected?
  • 抱歉,为了简化查看,省略了一些元素。我已经添加了它们。 checkElementIsSelected 应该防止重复按钮被推入数组
  • 你想举一个非常简单的例子来说明你想要达到的目标吗?
  • 嘿,是的,我添加了一张我所拥有的照片 :) @roll

标签: javascript arrays json reactjs react-native


【解决方案1】:

this.state.active 中只有一个布尔值作为活动标志。

将this.state.active 更改为一个对象,其键对应于 btn 名称,并为每个按钮存储一个布尔标志。

【讨论】:

    【解决方案2】:

    问题是这个active={this.state.active} 您只使用一个 state.active 来管理所有按钮。您需要为每个按钮设置一个状态。 这里和例子

            state {
                btnA:false,
                btnB:false,
                btnC:false
            }
    
            changeState = (btn) => {
                if(btn === 'a'){
                    this.setState( prevState => {
                        return {
                            btnA:  !prevState.btnA
                        }
                    })
                }
                .... same for btnB and btn C
            }
            ...
    
            return (
                <div>
                    <button onClick={this.state.changeState('a')} >{this.state.btnA?'Btn A is active':'Btn A is not active'}<button>
                    <button onClick={this.state.changeState('b')} >{this.state.btnB?'Btn B is active':'Btn B is not active'}<button>
                    <button onClick={this.state.changeState('c')} >{this.state.btnB?'Btn C is active':'Btn C is not active'}<button>
                </div>
            )
    

    这只是一个关于如何仅使用一种状态管理按钮状态的示例,现在将此示例适应您的代码

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多