简体   繁体   English

e.preventDefault() 不是 Reactjs 中的函数,使用了绑定

[英]e.preventDefault() is not a function in Reactjs, bind used

I'm new to react, i want to pass an a value as an argument when the user clicks, and also preventDefault, i found this question that suggest using bind i used it as the code below but didnt solve my problem, it gave me the error TypeError: e.preventDefault is not a function .我是新来的反应,我想在用户单击时传递一个值作为参数,并且还防止默认,我发现这个问题建议使用绑定我将它用作下面的代码但没有解决我的问题,它给了我错误TypeError: e.preventDefault is not a function


  constructor(props){
    super(props)
    this.state={
      headline:'',
      articles:[],
      article:[],
    }
  }


componentDidMount(){
  axios.get("http://127.0.0.1:5000/api/v1/news")
  .then(res=>{this.setState({articles:res.data})}
  )
}




browse = (e,id) => {
  console.log(e)
  e.preventDefault()
  console.log(id)
  axios.get("http://127.0.0.1:5000/api/v1/news/"+id)
  .then(res=>{this.setState({article:res.data,});console.log(res.data)})
}

Here's where i use the browse method

  {this.state.articles.map(art=> {return (
                     <tr>
                    <td><a href={art.url}>{art.headline}</a></td>
                    <td>{art.topic}</td>
                    <td>{art.author}</td>
                    <td><button  onClick ={this.browse.bind(this,art._id.$oid)} > Browse </button></td>
                                            </tr>
                                      )})}

Here's the error这是错误

×
TypeError: e.preventDefault is not a function
App.browse
src/App.js:36
  33 |         }
  34 | 
  35 | browse = (e,id) => {
> 36 |   e.preventDefault()
  37 |   axios.get("http://127.0.0.1:5000/api/v1/news/"+id)
  38 |   .then(res=>{this.setState({article:res.data,});console.log(res.data)})
  39 | }
View compiled

Actually, by writing onClick in that way, you are calling the function as the component is rendered and the passed "e" is not the event, so e.preventDefault() is not a function.实际上,通过以这种方式编写 onClick,您是在呈现组件时调用该函数,并且传递的“e”不是事件,因此 e.preventDefault() 不是函数。

For binding onClick without calling it at the runtime and passing "event" you can use the following format as mentioned here :对于绑定 onClick 而不在运行时调用它并传递“事件”,您可以使用此处提到的以下格式:

onClick={(e) => this.browse(e, id)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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