Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 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 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...