react slot传递

 子组件(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); // 原有 onClick
          if (action === 'confirm') handleConfirm();
          else if (action === 'cancel') handleCancel();
        };
    
        return React.cloneElement(child, { onClick });
      });
    
      return (
        
    setInputValue(e.target.value)} /> {childrenWithProps}
    ); };

     父组件调用

    父组件通过 onConfirm 和 onCancel 接收子组件值:

const ParentComponent = () => {
  const handleConfirm = (value) => {
    console.log('提交的值:', value);
  };

  const handleCancel = () => {
    console.log('操作取消');
  };

  return (
    
      
      
    
  );
};

 

你可能感兴趣的:(react.js,javascript,前端)