react中的插槽

本文介绍了如何在React中创建可复用的CustomWrapper组件,以及如何处理prop中的children属性,并展示了ref在输入框聚焦操作中的应用。
摘要由CSDN通过智能技术生成
import React from 'react';

// 定义一个可以接收子元素作为内容的封装组件
function CustomWrapper({ children }) {
  return (
    <div className="custom-wrapper">
      {/* 使用children prop来插入任何传入的内容 */}
      {children}
    </div>
  );
}

function App() {
  return (
    <CustomWrapper>
      {/* 在这里传递需要被包裹在自定义组件内部的内容 */}
      <h1>Hello, World!</h1>
      <p>This is a paragraph inside the CustomWrapper.</p>
    </CustomWrapper>
  );
}

export default App;

带有其他值(prop)的代码

  function Aaa(prop) {
    console.log(prop);
    const { name, age, children } = prop
    return (
      <div className="custom-wrapper">
        {/* 使用children prop来插入任何传入的内容 */}
        <div>qqqqqqqqqqqq</div>
        {prop.children}
      </div>
    );
  }

  return (
    <>
      <Aaa name="111111" age="234345">
        <div>2132</div>
      </Aaa>
    </>
  )

把children从prop中分离出来

  function Aaa(prop) {
    console.log(prop);
    const { ...rest, children } = prop
    return (
      <div className="custom-wrapper">
        {/* 使用children prop来插入任何传入的内容 */}
        <div {...rest}>qqqqqqqqqqqq</div>
        {prop.children}
      </div>
    );
  }

  return (
    <>
      <Aaa name="111111" age="234345">
        <div>2132</div>
      </Aaa>
    </>
  )

带有ref的传值

import React, { forwardRef } from 'react';
 
const FancyInput = forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});
 
const ParentComponent = () => {
  const inputRef = useRef(null);
 
  const handleClick = () => {
    inputRef.current.focus();
  };
 
  return (
    <div>
      <FancyInput ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃饭的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值