简体   繁体   中英

Why does passing event handler to child component not work

I am experimenting with passing event handlers to parent components so I wrote this code:

 import React, { useState } from "react"; export default function App() { const [val, setVal] = useState(""); function handleChange(event) { console.log(event.target); setVal(event.target.value); } return ( <div className="App"> <TextInput onChange={handleChange} /> <div>{val}</div> </div> ); } function TextInput(props) { return <input onChange={props.handleChange} type="text" />; } const rootElement = document.getElementById("root"); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, rootElement );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

(I don't know why stackoverflow cant handle export in above code, how do I make that work? Here is codesandbox -https://codesandbox.io/s/onchange-test-1pxdr?file=/src/index.js )

I would expect when typing in box the text under the box should update but nothing happens and no error. Why is this?

The error that you did is pretty simple. The rule of passing props is that you cannot access it in the child component by the same name you have given to the function in parent component.

Your function name:

function handleChange(event)

Access it by the name you have passed in as props which is onChange and not handleChange in this case:

<TextInput onChange={handleChange} />

You can use two ways at the child component props.onChange :

 <input onChange={props.onChange} type="text" />

or by using props destructuring:

function TextInput({onChange}) {
 <input onChange={onChange} type="text" />
}

It should be onChange={props.onChange}

  function TextInput(props) {
      return <input onChange={props.onChange} type="text" />;
    }

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