簡體   English   中英

將參數傳遞給無狀態功能組件中的事件函數

[英]Passing parameters to an event function in a Stateless Functional Component

我有一個嘗試將keyDown綁定到的播放列表..問題是我無法像使用庫一樣使用典型的React.Component( https://github.com/clauderic/react-sortable-hoc ),這要求我使用功能性的無狀態組件(SortableContainer)。 所以我什至無法訪問道具或狀態。 我試圖將數據作為參數傳遞而沒有任何效果。

這可行,但是我需要以某種方式將數據傳遞到handleKeyDown ..特別是我真的想以某種方式將“ props”傳遞到handleKeyDown中。

function handleKeyDown(e) {
  // **** I need some way to access outside data in here some how..
  //      whether it's passed as a parameter or any other way
  console.log(e.keyCode);
}

const PlaylistPages = SortableContainer(( props ) => {
  return (
    <div className="playlist-sortable" onKeyDown={handleKeyDown} tabIndex="0">
    // etc
  );
}

使用箭頭函數 ,並在handleKeyDown函數內部傳遞props和event對象。

像這樣寫:

onKeyDown = { e => handleKeyDown(props, e)}

handleKeyDown(props, e){
   console.log(e.target, props);
}

我認為更好的寫作方式是:

onClick={clickHandler(passedData)}

clickHandler= (passedData) => (e) => {
  console.log(e)
  console.log(passedData)
}

箭頭功能會導致不必要的重新渲染。

您可以將參數傳遞給高階函數,這將為您解決問題

function handleKeyDown(passedData) {
    return e => {
        console.log(passedData); // hello
        console.log(e.keyCode);
    }
}

const PlaylistPages = SortableContainer(( props ) => {
  const dataToPass = 'hello'
  return (
    <div className="playlist-sortable" onKeyDown={handleKeyDown(dataToPass)} tabIndex="0">
    // etc
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM