e.target.value返回我提交的表单中输入的值
e包含一个奇怪的React更改对象SyntheticEvents?
return (
<div>
<form onSubmit={ onSubmitName }>
<input id="name_field"
title="Name:"
placeholder={ user.name }/>
</form>
</div>
)
^上面是我的表单,下面是onSubmit,它位于Redux mapDispatchToProps内部
const mapDispatchToProps = (dispatch) => {
return {
onSubmitName: (e) => {
console.log('e', e);
e.preventDefault();
const name = document.getElementById('name_field').value;
dispatch({ type: "CHANGE_NAME", payload: handleOnSubmit(name) })
}
}
}
新转换的event
上不再存在e.preventDefault。
现在如何处理React?该文档没有提供解决方法。让e.preventDefault()
再次发挥作用e.target.value
import React from "react"
import { connect } from "react-redux"
const handleOnSubmit = (e) => {
e.preventDefault();
const name = document.getElementById('name_field').value;
return name;
}
const mapDispatchToProps = (dispatch) => {
return {
onSubmitName: (e) => {
console.log('e', e);
e.preventDefault();
const name = document.getElementById('name_field').value;
dispatch({ type: "CHANGE_NAME", payload: handleOnSubmit(name) })
}
}
}
const NameField = ({ user, onSubmitName }) => {
return (
<div>
<form onSubmit={ onSubmitName }>
<input id="name_field"
title="Name:"
placeholder={ user.name }/>
</form>
</div>
)
}
const NameContainer = connect(
mapDispatchToProps
)(NameField);
export default NameContainer;
答案 0 :(得分:1)
我在您的代码中看到的错误是您将name
传递给handleOnSubmit
,然后尝试preventDefault
,因为name
是一个字符串,因此会失败输入值)不是事件。您不需要preventDefault
两次。
const name = document.getElementById('name_field').value
dispatch({
type: "CHANGE_NAME",
payload: handleOnSubmit(name) // name is a string
})
调用:
const handleOnSubmit = (e) => { // e is name, not event.
e.preventDefault(); // crashes
..
..
}
我认为您可以删除外部函数,处理阻止映射调度调用中的默认行为。
最后,您的代码应如下所示:
import React from "react"
import { connect } from "react-redux"
const mapDispatchToProps = (dispatch) => {
return {
onSubmitName: e => {
e.preventDefault()
const name = document.getElementById('name_field').value
dispatch({ type: "CHANGE_NAME", payload: name })
}
}
}
const NameField = ({ user, onSubmitName }) => {
return (
<div>
<form onSubmit={onSubmitName}>
<input
id="name_field"
title="Name:"
placeholder={user.name}
/>
</form>
</div>
)
}
const NameContainer = connect(
null,
mapDispatchToProps
)(NameField)
export default NameContainer
可以查看我制作的webpackbin
答案 1 :(得分:0)
您在input
元素上缺少null
道具。此外,您需要将connect
作为第一个参数传递给const NameField = ({ user, onSubmitName }) => {
return (
<div>
<form onSubmit={ onSubmitName }>
<input id="name_field"
title="Name:"
placeholder={ user.name }
value={ user.name }
/>
</form>
</div>
)
}
mapDispatchToProps
在const mapDispatchToProps = (dispatch) => {
return {
onSubmitName: (e) => {
// use e.target.value
}
}
}
:
{{1}}