简体   繁体   中英

How to pass a function as a prop to React function component?

Im trying to pass a function down as a prop. Why is this not working?

In Parent:

const dummyProps = {
    label: "Text",
    increment: function() {
        console.log("+");
    },
};

function Parent() {
    return (
        <div>
            <Child {...dummyProps} />
        </div>
    );
}

In Child:

function InputNumeric({ label, increment }) {
    return(
        <label>{label}</label>
        <button onClick={increment}>Click</button>
    )
}

In React, you need to have a single parent element that is rendered. In your question you forgot to wrap the elements inside the child component. You can wrap with another element or with a React.Fragment (shorthand syntax is <> </> )

function InputNumeric({ label, increment }) {
    return(
        <>
          <label>{label}</label>
          <button onClick={increment}>Click</button>
        </>
    )
}

Remember,

<div prop1={'asdf'}></div>

is actually translated to

React.createElement('div', {prop1: 'asdf'})

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