gpt4 book ai didi

javascript - ReactJS无法获取输入的e.target.value

转载 作者:行者123 更新时间:2023-12-03 04:12:06 24 4
gpt4 key购买 nike

预期

e.target.value 返回我提交的表单中输入的值

结果

e 包含一个奇怪的 React 更改对象,SyntheticEvents

return (
<div>
<form onSubmit={ onSubmitName }>
<input id="name_field"
title="Name:"
placeholder={ user.name }/>
</form>
</div>
)

^ 上面是我的表单,下面是 Redux mapDispatchToProps 内部的 onSubmit

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

e.preventDefault 在新转换的事件上不再存在。 enter image description here

现在 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;

最佳答案

我在您的代码中看到的错误是,您将 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我做了

关于javascript - ReactJS无法获取输入的e.target.value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44290128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com