我正在尝试更改PressButton类组件中"currNum“的状态,并在Header类组件中呈现它,但我看不到这是可行的。这是代码。我已经在App类中定义了状态,并尝试在PressButton类中更改它,这是允许的,如果不允许,我如何实现这一点。
import React from 'react';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
score: 0,
prevNum: 1,
currNum: 0
}
};
render()
{
return(
<div>
<PressButtons currNum={this.state.currNum} prevNum={this.state.prevNum} prevScore={this.state.score}/>
<Header score={this.state.score} currNum={this.state.currNum}/>
</div>
);
}
}
class Header extends React.Component {
render(){
console.log('curnum in headert is '+this.props.currNum);
return(
<div>
<h1>Current Number:{this.props.currNum}</h1>
<h1>Current score: {this.props.score}</h1>
</div>
);
}
}
class PressButtons extends React.Component {
constructor(props){
super(props);
this.clickOne = this.clickOne.bind(this);
}
clickOne(e){
e.preventDefault();
const val = 1;
const prev = this.props.prevNum;
var prevScore= this.props.prevScore;
var currNum=this.props.currNum;
console.log(prev);
console.log(prevScore);
if(val === prev)
{
prevScore+=1;
}
this.setState(()=>{
return {
score: prevScore ,
currNum: 1,
prevNum: 1
};
});
console.log('curnum is '+currNum);
}
render(){
return(
<div>
<table>
<tr>
<td><button onClick={this.clickOne}>One</button></td>
<td><button>Two</button></td>
<td><button>Three</button></td>
</tr>
<tr>
<td><button>Four</button></td>
<td><button>Five</button></td>
<td><button>Six</button></td>
</tr>
<tr>
<td><button>Seven</button></td>
<td><button>Eight</button></td>
<td><button>Nine</button></td>
</tr>
</table>
</div>
);
}
}
https://stackoverflow.com/questions/50777534
复制相似问题