简体   繁体   中英

How to pass arguments to function in functional component in React

How can I pass arguments to a function in functional component? As far as I know, creating function in jsx is not good practice right?

function MyComponent(props) {
  function handleChange(event, data){
    console.log(event.target.value);
    console.log(data);
  }
  return <button onClick={handleClick(??)} value='Foo'>Click</button>
}

You can keep function outside of functional component ,

MyComponent = (props) => {
  return <button onClick={(event, props.data) => handleChange(event, props.data)} value='Foo'>Click</button>
}
function handleChange(event, data){
  console.log(event.target.value);
  console.log(data);
}

There isnt anything particularly wrong with using a non-arrow function in React/jsx. People just use arrow-functions more often so they don't have to bind the this keyword.

Something like this would work perfectly fine.

function MyComponent(props) {
  function handleChange(event, data){
    console.log(event.target.value);
    console.log(props.data)
  }
  return <button onClick={(event, props.data) => handleChange(event)} value='Foo'>Click</button>
}

This will work

function MyComponent(props) {
  function handleChange(event, data){
    console.log(event.target.value);
    console.log(data)

  }
  return <button onClick={(event) => handleChange(event, 'Some Custom Value')} value='Foo'>Click</button>
}

Or if you only want to send the data property, you could do something like

function MyComponent(props) {
  function handleChange(data){
    console.log(data)

  }
  return <button onClick={(event) => handleChange('Some Custom Value')} value='Foo'>Click</button>
}

You can try this:

function MyComponent (props) {
  function handleClick(e) {
    console.log(e.target);
    another(props);
  }
  function another (props) {
    console.log(props);
  }

  return (
    <button onClick={handleClick}>Test</button>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM