子组件(FormContainer)实现
功能需求:
- 管理内部状态(如表单输入值)。
- 点击确认按钮时,将状态传递给父组件。
- 点击取消按钮时,执行清理操作。
import React, { useState } from 'react';const FormContainer = ({ children, onConfirm, onCancel }) => {const [inputValue, setInputValue] = useState('');// 确认按钮点击处理const handleConfirm = () => {onConfirm(inputValue); // 传递值给父组件};// 取消按钮点击处理const handleCancel = () => {setInputValue(''); // 清空状态onCancel(); // 通知父组件};// 克隆子元素,注入点击事件const childrenWithProps = React.Children.map(children, (child) => {const action = child.props['data-action'];// 合并原有 onClick 和自定义处理逻辑const childOnClick = child.props.onClick;const onClick = (e) => {childOnClick?.(e); // 原有 onClickif (action === 'confirm') handleConfirm();else if (action === 'cancel') handleCancel();};return React.cloneElement(child, { onClick });});return (<div><inputvalue={inputValue}onChange={(e) => setInputValue(e.target.value)}/>{childrenWithProps}</div>); };
父组件调用
父组件通过
onConfirm
和onCancel
接收子组件值:
const ParentComponent = () => {const handleConfirm = (value) => {console.log('提交的值:', value);};const handleCancel = () => {console.log('操作取消');};return (<FormContainer onConfirm={handleConfirm} onCancel={handleCancel}><button data-action="confirm">确认</button><button data-action="cancel">取消</button></FormContainer>);
};