代码之家  ›  专栏  ›  技术社区  ›  user3142695

如何在函数调用中传递变量?

  •  0
  • user3142695  · 技术社区  · 4 年前

    在我的函数组件中,我调用了两个函数,它们的作用几乎相同:

    const App = () => {
        const handleOnClickFirst = () => {
          setValue('first')
        }
        const handleOnClickSecond = () => {
          setValue('second')
        }
    
        return (
            <div>
                {anything === true
                ? <Button onClick={handleOnClickFirst} />
                : <Button onClick={handleOnClickSecond} />}
            </div>
        )
    }
    

    const handleOnClick = (value) => {
        setValue(value)
    }
    

    但是我如何传递这个值呢 onClick ?

    2 回复  |  直到 4 年前
        1
  •  2
  •   Armen    4 年前

    onClick={(event) => handleOnClick(value)}
    

    onClick={function(event){ handleOnClick(value) }}
    

    如果你不需要活动,你可以这样传递

    onClick={() => handleOnClick(value)}
    

    class App extends React.Component {
      handleOnClick(val) {
        console.log(`${val}`);
      }
      render() {
        return (
          <button onClick={this.handleOnClick.bind(this, "test")}>
            click me
          </button>
        );
      }
    }
    
        2
  •  1
  •   Arbin Shrestha    4 年前

    你能做到的

     onClick={() => handleOnClick(value)}
    

    更多信息请参见: https://reactjs.org/docs/faq-functions.html

        3
  •  1
  •   Harmandeep Singh Kalsi    4 年前

    您可以这样做:

    <button onClick={(event)=>handleOnClick(<pass your paramter here>)}></button>
    
        4
  •  -1
  •   Alfonso Piedrasanta    4 年前

    试试这个:

    const App = () => {
         const handleOnClick = (passedInValue) => {
              setValue(passedInValue)
         }
         return (
              <div>
                   {anything === true
                   ? <Button onClick={() => handleOnClick("first")} />
                   : <Button onClick={() => handleOnClick("second")} />}
              </div>
          )
        }