动态反应设置状态属性及其值 [英] React set state property and its value dynamically
本文介绍了动态反应设置状态属性及其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下组成部分:
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;
是否可以选择需要更新哪些状态属性及其值?
Is it possible to choose what state property needs updating together with its value?
我已经尝试过了:
hideSingleGrid(el, val) {
this.setState({
el: val
})
}
以便它可以像这样使用:
so that it could be used like:
this.hideSingleGrid(n2, true);
this.hideSingleGrid(n1, true);
但是它不起作用(状态没有更新).
but it doesn't work (state doesn't get updated)..
推荐答案
您可以通过两种方式进行操作:
You can do it two ways:
var s = {};
s[el] = val;
this.setState(s);
或发烧友:
this.setState({[el]: val})
假设el
是要更新的属性的名称.
Assuming el
is a name of the property to update.
这篇关于动态反应设置状态属性及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文