动态设置状态属性及其值

时间:2017-08-24 12:50:31

标签: javascript reactjs ecmascript-6

我有以下组件:

import React, { Component } from 'react';

import Action from './action.jsx';
import SingleGridEl from './singleGridEl.jsx';

class Grid extends Component {

    constructor(props) {
        super(props);
        this.maxN = 110;
        this.tempArray = [];
        this.question;

        this.state = {
            n1: false,
            n2: false,
            n3: false,
            n4: false,
            n5: false,
            n6: false
        }

        this.hideSingleGrid = this.hideSingleGrid.bind(this);
    }

    getRandomN() {
        var randomN = Math.floor((Math.random() * this.maxN) + 1);

        if(this.tempArray.indexOf(randomN) === -1) {
            this.tempArray.push(randomN);
        }
        else {
            randomN = this.getRandomN();
        }

        return randomN;
    }

    getRandomQuestion() {   
        this.question = this.props.current.data.questions[this.getRandomN()];
        return this.question;
    }

    hideSingleGrid(el, val) {
        this.setState({
            el: val
        })

        console.log('sdfsdf');
    }

    render() {
        this.getRandomQuestion();

        return (
            <section className="game">
                <div className="grid">

                    <div className="row">
                        <SingleGridEl visibility={this.state.n1} />
                        <SingleGridEl visibility={this.state.n2} />
                        <SingleGridEl visibility={this.state.n3} />
                        <SingleGridEl visibility={this.state.n4} />
                        <SingleGridEl visibility={this.state.n5} />
                        <SingleGridEl visibility={this.state.n6} />
                    </div>
                </div>

                <Action t={this.hideSingleGrid} question={this.question} getRandomQuestion={this.getRandomQuestion.bind(this)}/>
            </section>
        );
    }
}

export default Grid;

是否可以选择需要更新的州财产及其价值?

我试过这个:

hideSingleGrid(el, val) {
    this.setState({
        el: val
    })
}

以便可以像:

一样使用
this.hideSingleGrid(n2, true);
this.hideSingleGrid(n1, true);

但它不起作用(状态不会更新)..

1 个答案:

答案 0 :(得分:1)

你可以用两种方式做到:

var s = {};
s[el] = val;
this.setState(s);

或一点fancier

this.setState({[el]: val})

假设el是要更新的属性的名称。