创建一个用于拆分字符串的自定义钩子(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>



我非常兴奋能加入社区!谢谢你,保重。

Lucie Bachman

自定义挂钩是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>
);
}

最新更新