我試圖呈現需要組件,當我們點擊「添加」鏈接。 下面是我的主要成分代碼:渲染點擊反應組件
import React from 'react';
import ReactDOM from 'react-dom';
import { Hand } from './hand.js';
import { Need } from './need.js';
class App extends React.Component{
constructor() {
super();
this.processHand = this.processHand.bind(this);
this.addNeed = this.addNeed.bind(this);
this.state = {
inhandMoney : " ",
renderNeed: false,
}
}
processHand(e){
e.preventDefault();
const handMoneyReceived = this.handMoney.value;
this.setState({
inhandMoney: handMoneyReceived
});
}
addNeed(e){
e.preventDefault();
this.setState({
renderNeed:true
});
}
render(){
const passNeed = (
<Need/>
);
return(
<div>
<div className ="hand">
<form onSubmit = {this.processHand}>
<input type="text" ref= {ref => this.handMoney = ref}/>
<input type="submit"/>
</form>
<Hand handMoney = {this.state.inhandMoney}/>
<Need/>
</div>
{this.state.renderNeed ? passNeed : null}
<a href="#" className="add" onClick = {this.addNeed}>add</a>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
以下是我的極品部件,以防萬一:
import React from 'react';
export class Need extends React.Component{
constructor() {
super();
this.processNeed = this.processNeed.bind(this);
this.state ={
why: " ",
howMuch: 0
}
}
processNeed(e){
e.preventDefault();
const why=this.why.value;
const howMuch=this.howMuch.value;
this.setState({
why:why,
howMuch:howMuch
});
}
render(){
return(
<div className ="need">
<form onSubmit = {this.processNeed}>
<input type="text" ref= {ref => this.why = ref}/>
<input type="text" ref= {ref => this.howMuch = ref}/>
<input type="submit"/>
</form>
<div>
<h1>{this.state.why}</h1>
<h1>{this.state.howMuch}</h1>
</div>
</div>
)
}
}
我正在實現我所試圖實現對第一次點擊到add鏈接,即首先需要組件被渲染,沒有任何條件。當我點擊「添加」需要組件再次呈現,但是當我第二次單擊「添加」鏈接時,我沒有看到任何更改。爲什麼是這樣,我想每次點擊「添加」鏈接時呈現需要組件。
類方法需要被「綁定」。 @john_omalley的答案如下。請參閱http://stackoverflow.com/a/30721098/368697瞭解您打算用作回調的綁定類方法。 –
你有沒有得到解決方案或仍然面臨問題? –