Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - 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

What is wrong here?

question from:https://stackoverflow.com/questions/65891706/how-to-pass-data-from-parent-to-children-with-react-hooks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pay attention to props name. You're passing from parent a property called setErrors while in child component you're looking for errors. Try to rename property from setErrors to errors or simply read setErrors from <Input /> component


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...