我想将 onChange
从 child 传递给 parent 。我什至不知道这是否是正确的表达方式。但这是我的代码。该代码以前有效,但我正在尝试将我的代码分解为更小的组件并处理错误。如果您想要更多代码,我很乐意与您分享。我对 React 有点陌生。我不知道我做错了什么。错误基本上是接受 event
的函数没有得到任何东西。
家长:
<Inputs hasInputs={hasInputs} onSubmit={this.handleSubmit} thoughtProp={this.state.thought} onChange={this.handleChange} />
child :
import React from 'react'
import { Input } from '../Input.js'
export const Inputs = (props) => {
return (
<form className="flex-item-main form" onSubmit={props.onSubmit}>
<ol>
{props.thoughtProp.map((input, index) => (
<Input type='text' onSubmit={props.onSubmit} key={index} value={input} onChange={(event) => props.onChange(event, index) } className='textInputs' />
))}
{ props.hasInputs ? (
<input className='submitThoughts' type='submit' value='Submit Thought!' />
) : (
null
)}
</ol>
</form>
)
}
最佳答案
在 React 中使用钩子(Hook)从子组件更改父组件状态
子组件包含输入字段,我们将把输入字段值发送给父组件。因此,让我们先创建 Parent 组件。
Parent.js
import Child from "./Child";
function Parent() {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const onChangeName=(newValue)=>{
setName(newValue);
}
const onChangePassword=(value)=>{
setPassword(value);
}
// We pass a callback to Child
return (
<Child onChangeName={onChangeName} onChangePassword={onChangePassword} />;
)}
如您所见,我们将 onChange 属性设置为子组件。下一步是创建子组件。
Child.js
function Child(props) {
return(
<input onChange={(e)=>{props.onChangeName(e.target.value)}} />
<input onChange={(e)=>{props.onChangePassword(e.target.value)}} />
)}
在上面的代码中,我们创建了函数 handleChange,它将通过 props.onChange 将值传递给我们的父组件。
关于javascript - 在 React 中将 onChange 事件从子级传递给父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62334342/