React Redux - Dispatch retrieve input value

2019-08-13 00:25发布

问题:

I have the following React view/render function:

let BaseSalaryView = ({ counter, onChange }) => (
    <div>
        <input type="text"
            placeholder="Annual Salary"
            value={counter}
            onChange={() => onChange(counter)} />
        <span>Try: {counter}</span>
    </div>
)

I am trying to figure out how I can pass in the value that just got changed, into my onChange dispatch handler.

Attempts

I have tried the following but they are all undefined.

onChange={() => onChange(this.input.value)}> 
onChange={() => onChange(input.value)}> 
onChange={() => onChange(value)}> 

Rest of code

const mapDispatchToProps = (dispatch) => {
    return {
        onChange: (counter) => {
            dispatch(baseSalaryChange(counter)) // Need the input v alue here
        }
    }
}

export function baseSalaryChange(baseSalary) {
  return { type: BASE_SALARY_CHANGED, baseSalary }
}

The actions get called, but coutner is always set to the initial value.

回答1:

OMG after 2 hours of struggling, 2 mins after I posted the question I figure it out.

Need to take in a parameter into the inline function of onChange, which will get set to the event that just happened. Then I can access the event.target from there:

onChange={(event) => onChange(event.target.value)} />