React Redux - Dispatch retrieve input value

自作多情 提交于 2019-12-24 17:08:56

问题


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


来源:https://stackoverflow.com/questions/36663573/react-redux-dispatch-retrieve-input-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!