首页 > 解决方案 > 创建用于拆分字符串的自定义 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>



我很高兴能加入社区!谢谢你,保重。

露西·巴赫曼

标签: reactjsreact-hooks

解决方案


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

推荐阅读