多个侦听器上的单个处理程序响应 [英] Single handler on multiple listener on react
本文介绍了多个侦听器上的单个处理程序响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图使用es6来制作没有多个处理程序的动态状态,但是我被卡住了。我不知道下面的代码有什么问题
Were trying to use es6 to make dynamic state without multiple handlers but I'm stuck. I've no clue what's wrong with my code below
<div className="row-wrap">
<span>Mon</span>
<input name="1_min" onChange={this.handleAdvancePrice} type="text" />
<input name="1_max" onChange={this.handleAdvancePrice} type="text" />
</div>
<div className="row-wrap">
<span>Tue</span>
<input name="2_min" onChange={this.handleAdvancePrice} type="text" />
<input name="2_max" onChange={this.handleAdvancePrice} type="text" />
</div>
<button onClick={this.showStates}></button>
..
..
handleAdvancePrice = (e) => {
let dow = e.target.name.split('_')[0],
type = e.target.name.split('_')[1],
value = +(e.target.value);
console.log(dow, type) // it print correctly
this.setState = ({
[`advancePrice_${dow}_${type}`]: value
})
}
showStates = () => {
console.log(this.state) //error this.setState is not a function, caused by handleAdvancePrice
}
我检查了我的其他功能,handleAdvancePrice是罪魁祸首,但它有什么问题?
I've checked my other function, handleAdvancePrice is the culprit, but what's wrong with it?
推荐答案
罪魁祸首是 this.setState
之后的额外 =
符号。此外,不需要使用类型和dow
分开;因为它可以直接使用 e.target.name
the culprit is the extra =
sign after this.setState
. Also there is not need to use type and dow
separate;y since it is available to you directly with e.target.name
class App extends React.Component {
constructor() {
super();
this.state = {}
}
handleAdvancePrice = (e) => {
let dow = e.target.name;
let value = e.target.value;
this.setState ({
[`advancePrice_${dow}`]: value
})
}
showStates = () => {
console.log(this.state) //error this.setState is not a function, caused by handleAdvancePrice
}
render() {
return (
<div>
<div className="row-wrap">
<span>Mon</span>
<input name="1_min" onChange={this.handleAdvancePrice} type="text" />
<input name="1_max" onChange={this.handleAdvancePrice} type="text" />
</div>
<div className="row-wrap">
<span>Tue</span>
<input name="2_min" onChange={this.handleAdvancePrice} type="text" />
<input name="2_max" onChange={this.handleAdvancePrice} type="text" />
</div>
<button onClick={this.showStates}>Show</button>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
这篇关于多个侦听器上的单个处理程序响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文