所以我试图创建一个可用于在事件中传递的不同键值上设置状态的函数。当我记录状态时,它仍处于初始状态,每个键上都有空字符串。我尝试使用和不使用[]来设置setState中的键值。谢谢
constructor(props){
super(props)
this.state={
Day:'',
Open:'',
Close:''
}
}
logState(){
console.log(this.state);
}
pushTime(event){
event.preventDefault();
console.log('Clicked ', event.target.id, event.target.value);
var id = event.target.id
console.log(typeof id);
this.setState({[event.target.id]:event.target.name})
}
答案 0 :(得分:1)
您需要绑定pushTime
函数,以便它可以访问该状态。为此,您可以使用arrow function
或bind it in constructor
。另外setState
需要时间来改变状态,所以你必须在setState
回调中调用logState函数,如下例所示
class App extends React.Component {
constructor(props){
super(props)
this.state={
Day:'',
Open:'',
Close:''
}
}
logState(){
console.log(this.state);
}
pushTime = (event) =>{
event.preventDefault();
console.log('Clicked ', event.target.id, event.target.value);
var id = event.target.id
this.setState({[id]:event.target.name}, function() {
this.logState();
})
}
render() {
return (
<div>
<input type='checkbox' id='Day' name='Day' onClick={this.pushTime} value='Day'/>
<input type='checkbox' id='Open' name='Open' value='Open' onClick={this.pushTime}/>
<input type='checkbox' id='Close' name='Close' value='Close' onClick={this.pushTime}/>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
&#13;
答案 1 :(得分:1)
除了@ Shubham的回答,你也可以设置这样的状态:
class App extends React.Component {
constructor(props){
super(props)
this.state={
Day:false,
Open:false,
Close:true
}
this.pushTime = this.pushTime.bind(this);
}
logState(){
console.log(this.state);
}
pushTime(event){
let state = this.state;
console.log('Clicked ', event.target.id, event.target.value);
state[event.target.id]=!state[event.target.id];
this.setState({state});
}
render() {
return (
<div>
<input type='checkbox' id='Day' name='Day' onClick={this.pushTime} checked={this.state.Day}/>
<input type='checkbox' id='Open' name='Open' onClick={this.pushTime} checked={this.state.Open}/>
<input type='checkbox' id='Close' name='Close' onClick={this.pushTime} checked={this.state.Close}/>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
&#13;
检查jsfiddle
:https://jsfiddle.net/vhavwcbh/
答案 2 :(得分:0)
pushTime(event){
event.preventDefault();
var stateObject=function(){
let returnObj={}
returnObj[this.target.id]=this.target.value
return returnObj
}.bind(event)();
this.setState(stateObject)
}