我有一个父组件,它通过我的数组进行映射,并打印出各种Child组件的迭代。
我试图在父组件中访问状态,但无法弄清楚如何从子组件中提取“inputValue”的正确状态,并将其放在父组件中。
理想情况下,我希望inputValue和isValidated状态都存在于父组件中,以便我可以在各种基于表单的函数中使用它们。
父组件:
import React, { useState } from 'react';
import { formFieldsData } from './FormFields';
import Input from './Input';
export default function Form() {
return (
<form>
{formFieldsData.map((item) => (
<Input
key={item.id}
id={item.id}
label={item.label}
type={item.type}
placeholder={item.placeholder}
/>
))}
</form>
)
}
子组件:
import React, { useState } from 'react';
import styles from './forms.module.scss';
import RangeInput from './RangeInput';
export default function Input({ type, id, placeholder = '', label, props }) {
const [inputValue, setInputValue] = useState('');
const [isValidated, setIsValidated] = useState(false);
const isRangeInput = type === 'range';
const handleChange = (e) => {
setInputValue(e.target.value)
if(inputValue.length > 0 || type === 'date') {
setIsValidated(true)
}
}
return (
<div className={styles.form__row}>
<label htmlFor={id}>{label}: {inputValue}</label>
{isRangeInput
? <RangeInput id={id} onChange={(e) => handleChange(e)} />
: <input
required
type={type}
id={id}
name={id}
placeholder={placeholder}
className={styles.input}
value={inputValue}
onChange={(e) => handleChange(e)}
/>
}
<button type="submit" id="formSubmit" onClick={() => alert('button click catched')} disabled={!isValidated}>Submit!</button>
</div>
)
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
最简单的方法是在父组件中管理状态。然后,您只需要将一个函数作为prop传递给子组件,以更新父组件的状态。这是我之前回答一个相关问题的示例,演示了如何从子组件传递数据给父组件。
请注意,只有在直接子组件中进行这种prop drilling才是合适的。如果父子组件之间的层级关系扩展,则更适合使用上下文/状态管理。