[英]How to pass data from parent to children with react hooks
I have a simple modal in which I have a form on submit I display errors now I want to pass these errors to the children component.我有一个简单的模式,其中我有一个提交表单我现在显示错误我想将这些错误传递给子组件。
Here is a simplified parent component这是一个简化的父组件
import React from 'react';
import Input from 'components/Functional/Input';
function Parent() {
const [errors, setErrors] = useState([]);
const handleSubmit = async e => {
const formData = new FormData();
}
return (
<Modal handleSubmit={handleSubmit}>
<Input setErrors={errors} ></Input>
</Modal>
)
}
export default Parent
Here is my children component这是我的孩子组件
import React from 'react'
function Input({errors}) {
const [field, setField] =useState('');
console.log('errors', errors)
return (
<div>
<input type="text" onChange={e => setField(e.target.value)} />
</div>
)
}
export default Input
Now when I submit the data with errors, the console.log('errors', errors)
in the children component I get undefined
现在,当我提交有错误的数据时,子组件中的
console.log('errors', errors)
我得到undefined
What is wrong here?这里有什么问题?
Pay attention to props name.注意道具名称。 You're passing from parent a property called
setErrors
while in child component you're looking for errors
.您正在从父组件传递一个名为
setErrors
的属性,而在子组件中您正在寻找errors
。 Try to rename property from setErrors
to errors
or simply read setErrors
from <Input />
component尝试将属性从
setErrors
重命名为errors
,或者简单地从<Input />
组件中读取setErrors
You seem to have a typo in your input component.您的输入组件中似乎有错字。 You set the prop
setErrors
but your component expects errors
.您设置了道具
setErrors
但您的组件需要errors
。 If you use plain javascript you should use proptypes to ensure this doesn't happen.如果你使用普通的 javascript 你应该使用 proptypes 来确保这不会发生。
import React from 'react'
import PropTypes from 'prop-types'
function Input({errors}) {
const [field, setField] =useState('');
console.log('errors', errors)
return (
<div>
<input type="text" onChange={e => setField(e.target.value)} />
</div>
)
}
Input.propTypes = {
errors: PropTypes.arrayOf(PropTypes.string)
};
export default Input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.