简体   繁体   中英

Why does preventDefault stop working when I try to use a function passed by props?

I have a component with a form and when I use this line of code the function passed by props works.

<form onSubmit={this.props.onCreateNewItem.bind(this)}>

If I try to create another function before the render that will run onCreateNewItem it stops working.

<form action="" onSubmit={this.onChangeTest}>

onChangeTest(event){
    event.preventDefault();
    this.props.onCreateNewItem();
  } 

If I run the code with out trying to call the function then the preventDefault works. If I try to run the function I get this error: "TypeError: Cannot read property 'preventDefault' of undefined." I tried to bind this and then preventDefault works but it does not run the function.

this.props.onCreateNewItem.bind(this);

I am confused because I can get the preventDefault to work without calling the function and I can get the function to work if I call it directly in the form but I can not get them both to work together.

You have to bind 'onChangeTest' method. Currently the this inside onChangeTest is referring to the form object not React component.

 class App extends React.Component { constructor(props) { super(props); this.onChangeTest = this.onChangeTest.bind(this); } onChangeTest(event){ event.preventDefault(); this.props.onCreateNewItem(); } render() { return ( <form action="" onSubmit={this.onChangeTest}> <button type="submit">Submit</button> </form> ); } } /// function onCreateNewItem() { console.log("onCreateNewItem called") } const rootElement = document.getElementById("root"); ReactDOM.render(<App onCreateNewItem={onCreateNewItem} />, 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> <div id="root"></div>

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