【发布时间】:2017-06-28 17:28:57
【问题描述】:
当我们单击“添加”链接时,我正在尝试呈现需要组件。 以下是我的主要组件代码:
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>
)
}
}
我正在实现我在第一次单击添加链接时想要实现的目标,即最初需要组件在没有任何条件的情况下呈现。当我单击“添加”时,需要组件再次呈现但是当我第二次单击“添加”链接,我没有看到任何更改。为什么会这样,每次点击“添加”链接时,我都想渲染 Need 组件。
【问题讨论】:
-
类方法需要“绑定”。 @john_omalley 的答案如下。请参阅stackoverflow.com/a/30721098/368697 了解您打算用作回调的绑定类方法。
-
您得到解决方案还是仍然面临问题??
标签: javascript reactjs react-jsx