react使用组件

使用组件 

现在你已经定义了 Profile 组件,你可以在其他组件中使用它。例如,你可以导出一个内部使用了多个 Profile 组件的 Gallery 组件:

function Profile() {
  return (
    <img
      src="https://i.imgur.com/MK3eW3As.jpg"
      alt="Katherine Johnson"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>了不起的科学家</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

浏览器所看到的 

注意下面两者的区别:

  • <section> 是小写的,所以 React 知道我们指的是 HTML 标签。
  • <Profile /> 以大写 P 开头,所以 React 知道我们想要使用名为 Profile 的组件。

然而 Profile 包含更多的 HTML:<img />。这是浏览器最后所看到的:

<section>
  <h1>了不起的科学家</h1>
  <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
  <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
  <img src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />
</section>

嵌套和组织组件 

组件是常规的 JavaScript 函数,所以你可以将多个组件保存在同一份文件中。当组件相对较小或彼此紧密相关时,这是一种省事的处理方式。如果这个文件变得臃肿,你也可以随时将 Profile 移动到单独的文件中。你可以立即在 关于引入的页面 中学习如何做到这些。

因为 Profile 组件在 Gallery 组件中渲染——甚至好几次!——我们可以认为 Gallery 是一个 父组件,将每个 Profile 渲染为一个“孩子”。这是 React 的神奇之处:你可以只定义组件一次,然后按需多处和多次使用。

组件可以渲染其他组件,但是 请不要嵌套他们的定义

export default function Gallery() {
  // 🔴 永远不要在组件中定义组件
  function Profile() {
    // ...
  }
  // ...
}

上面这段代码 非常慢,并且会导致 bug 产生。因此,你应该在顶层定义每个组件:

export default function Gallery() {
  // ...
}

// ✅ 在顶层声明组件
function Profile() {
  // ...
}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中实现拖拽组件的方法有多种,其中比较常用的是使用react-dnd库。下面是一个简单的使用示例: 1. 安装react-dnd和react-dnd-html5-backend: ``` npm install --save react-dnd react-dnd-html5-backend ``` 2. 创建可拖拽和可放置的组件: ```jsx import { useDrag, useDrop } from 'react-dnd'; function DraggableItem(props) { const [{ isDragging }, drag] = useDrag({ item: { type: 'item', id: props.id }, collect: monitor => ({ isDragging: monitor.isDragging(), }), }); return ( <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}> {props.children} </div> ); } function DroppableArea(props) { const [{ isOver }, drop] = useDrop({ accept: 'item', drop: (item, monitor) => { props.onDrop(item.id); }, collect: monitor => ({ isOver: monitor.isOver(), }), }); return ( <div ref={drop} style={{ backgroundColor: isOver ? 'lightgreen' : 'white' }}> {props.children} </div> ); } ``` 3. 在父组件使用可拖拽和可放置的组件: ```jsx function App() { const [items, setItems] = useState([1, 2, 3]); const handleDrop = (id) => { setItems(items.filter(item => item !== id)); }; return ( <div> {items.map(item => ( <DraggableItem key={item} id={item}> Item {item} </DraggableItem> ))} <DroppableArea onDrop={handleDrop}> Drop here </DroppableArea> </div> ); } ``` 在上面的示例中,`DraggableItem`组件是可拖拽的,`DroppableArea`组件是可放置的。当`DraggableItem`被拖拽到`DroppableArea`上时,会调用`handleDrop`函数删除该项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值