Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

javascript - Single handler on multiple listener on react

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
}

I've checked my other function, handleAdvancePrice is the culprit, but what's wrong with it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are not binding the proper context to your function handleAdvancePrice.

If you are building your component using ES6 Class then, you can bind the context to all your functions in constructor like this:

constructor() {
   this.handleAdvancePrice = this.handleAdvancePrice.bind(this);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...