【问题标题】:Passing parameters to an event function in a Stateless Functional Component将参数传递给无状态功能组件中的事件函数
【发布时间】:2017-08-28 18:42:25
【问题描述】:

我有一个播放列表,我正在尝试将 keyDown 绑定到.. 问题是我无法使用典型的 React.Component,因为我正在使用一个需要我使用功能性无状态的库 (https://github.com/clauderic/react-sortable-hoc)组件(可排序容器)。所以我什至无法访问道具或状态。我试图将数据作为参数传递,但没有任何效果..

这可行,但我需要以某种方式将数据传递给 handleKeyDown.. 特别是我真的想以某种方式将“道具”传递给 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
  );
}

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    使用arrow function,并在handleKeyDown函数中传递道具和事件对象。

    这样写:

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

    【讨论】:

      【解决方案2】:

      我认为更好的写作方式是:

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

      箭头函数会导致不必要的重新渲染。

      【讨论】:

      • 您能否详细说明一下这个解决方案?它确实有效,但理解这种行为并不简单。
      • 实际上是咖喱函数。请查看this 链接以获得更好的说明。
      【解决方案3】:

      你可以将你的参数传递给一个高阶函数,它会为你解决问题

      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
        );
      }
      

      【讨论】:

      • 是反模式吗? @ShubhamKhatri
      • 很抱歉没有看到您正在返回一个函数,但是 mayank 在 cmets 中所说的是速记
      猜你喜欢
      • 1970-01-01
      • 2019-09-18
      • 2022-12-21
      • 2020-07-22
      • 1970-01-01
      • 2021-02-28
      • 2021-01-27
      • 2020-09-07
      • 2020-02-09
      相关资源
      最近更新 更多