reactjs - 创建用于拆分字符串的自定义 Hook (React JS)
问题描述
我最近正在使用 React JS (hooks)。对于一个项目,我需要在不同的 div 中拆分许多字符串。所以,我为此创建了一个函数,这节省了我一些时间!我的实际问题是:我应该创建一个自定义 Hook 而不是我的函数吗?
当然,实际代码有效,但作为初学者,我不知道我的方式是否干净。我需要反馈,因为我的主要目标是尽可能写出最好和清晰的代码。
// Splitting Texts
const splitText = str => {
return (
<div>
{str.split(' ').map((item, index) => {
return (
<div key={index}>
{item}
</div>
);
})}
</div>
);
};
// Main App
export default function App() {
const name = splitText('Lucie Bachman');
const description = splitText('Hey, this is my first post on StackOverflow!');
return (
<div className="App">
<h1>{name}</h1>
<h2>{description}</h2>
</div>
);
}
预期成绩 :
<h1>
<div>
<div>Lucie</div>
<div>Bachman</div>
</div>
</h1>
我很高兴能加入社区!谢谢你,保重。
露西·巴赫曼
解决方案
自定义挂钩是that uses out of the box react hooks
实际提供逻辑并返回数据的东西。
如果函数返回 JSX,它实际上只是一个函数或者可以用作函数组件
由于您只想将字符串转换为组件并用于React.memo
优化渲染
// Splitting Texts
const SplitText = React.memo(({str}) => {
return (
<div>
{str.split(' ').map((item, index) => {
return (
<div key={index}>
{item}
</div>
);
})}
</div>
);
});
// Main App
export default function App() {
return (
<div className="App">
<h1><SplitText str={'Lucie Bachman'} /></h1>
<h2><SplitText str={'Hey, this is my first post on StackOverflow!''} /></h2>
</div>
);
}
推荐阅读
- c# - 在 ASP.Net Core 中从 html 助手自动转换为 asp 标签助手
- excel - 删除按钮以删除相关行和这些行中的所有按钮
- json - VS Code - 如何编写 tasks.json 以在单个任务中运行多个命令
- android - Flutter 调试错误“Gradle 构建未能生成 .apk 文件”
- payfort - payfort 无效的额外参数
- php - 使用 wp-ajax.php 处理查询字符串或类似内容
- python - 如果 {} 的变量不存在,有什么办法可以将空字符串填充到 {} 中?
- c++ - rand() 函数生成错误范围内的数字
- javascript - 如何在 React.js 中滚动时更改 Bootstrap 导航栏颜色?
- javascript - 如何从使用jQuery的切换按钮隐藏的div中获取文本?