3個React技巧

在Fragment上使用key值

const pokemons = ['Charizard', 'Mr. Mime', 'Jynx']

pokemons.map(pokemon => (
  <>
    <strong>Name: </strong>
    <span>{pokemon}</span>
  </>
))

空標籤不能加key值,但是可以使用React.Fragment代替

pokemons.map(pokemon => (
  <React.Fragment key={pokemon}>
    <strong>Name: </strong>
    <span>{pokemon}</span>
  </React.Fragment>
))

創建一個變量標籤

const Button = ({ as = 'button', ...props }) => React.createElement(as, props)

<Button>A Button</Button> // 渲染爲button按鈕
<Button as="a">A Link</Button> // 渲染爲a標籤

其實這個寫法不好,我們可以這樣,可以將屬性作爲組件來使用,react中稱爲render props

const Button = ({ Component = 'button', ...props }) => <Component {...props} />

<Button>A Button</Button> // 渲染爲button按鈕
<Button Component="a">A Link</Button> // 渲染爲a標籤

使用useReducer實現useState

如果直接從useReducer返回操作,則其行爲與useState幾乎相同。

function App() {
  const [name, setName] = useReducer((_, value) => value, '請輸入');
  return (
    <div className="App">
      <input value={name} onChange={e => setName(e.target.value)} />
    </div>
  );
}

export default App;

手動重新渲染組件

您是否需要手動重新渲染組件? 例如,您需要重新渲染組件,但是沒有任何狀態或可以觸摸的任何內容。 假設出於某種奇怪的原因,您想在單擊按鈕時執行此操作。

您可以執行以下操作:

function App() {
  const [, rerender] = useState()
  function handleRefresh () {
    rerender({})
  }
  return (
    <div className="App">
      <div>hello</div>
      <button onClick={handleRefresh}>按鈕</button>
    </div>
  );
}


export default App;

您使用useState,但實際上並不需要狀態本身。 您只需要setState函數來引起重新渲染。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章