[英]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.我有一个带有表单的组件,当我使用这行代码时,props 传递的函数会起作用。
<form onSubmit={this.props.onCreateNewItem.bind(this)}>
If I try to create another function before the render that will run onCreateNewItem it stops working.如果我尝试在将运行 onCreateNewItem 的渲染之前创建另一个函数,它将停止工作。
<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.如果我在不尝试调用函数的情况下运行代码,则 preventDefault 工作。 If I try to run the function I get this error: "TypeError: Cannot read property 'preventDefault' of undefined."
如果我尝试运行该函数,则会收到此错误:“TypeError:无法读取未定义的属性 'preventDefault'。” I tried to bind this and then preventDefault works but it does not run the function.
我试图绑定它,然后 preventDefault 工作,但它不运行该功能。
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.我很困惑,因为我可以在不调用函数的情况下让 preventDefault 工作,如果我直接在表单中调用它,我可以让函数工作,但我不能让它们一起工作。
You have to bind
'onChangeTest' method.您必须
bind
“onChangeTest”方法。 Currently the this
inside onChangeTest
is referring to the form
object not React component.目前
onChangeTest
的this
指的是form
对象而不是 React 组件。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.