教程:如何在React中发出HTTP请求,第2部分

如果尚未完成 本教程的 第1部分 ,请在开始第2部分之前完成。

现在我们已经使用create-react-app设置了项目 ,我们可以开始编写一些代码了 。 将您的项目打开到您选择的编辑器中,让我们开始删除一些create-react-app为您添加的样板,因为我们不需要它。

步骤1:删除create-react-app样板

当您进入App.js文件时,它将看起来像这样:

继续并从App.jsApp.css删除所有代码,并将App.css替换为以下代码:

 import React, { Component } from 'react'
import './App.css'
 class App extends Component {
render () {
return (
<div className='button__container'>
<button className='button'>Click Me</button>
</div>
)
}
}
 export default App

您也可以将此代码添加到App.css文件中。

.button__container {
margin-top: 200 px ;
text-align: center;
}
.button {
background-color:green;
border: none;
color: white;
font-size: 16 px ;
height: 40 px ;
width: 200 px ;
}

您也可以删除logo.svg文件,因为我们不会使用它。 现在,当您在终端中运行npm start时,您应该在浏览器中看到以下内容:

步骤2:连接handleClick函数

我们的下一步将建立一个功能,当用户单击按钮时将触发该功能。 我们将从在按钮上添加onClick事件开始,如下所示:

<button className='button' onClick={ this .handleClick}>
Click Me
</button>

单击按钮后,我们将调用绑定到this名为handleClick的函数。 让我们继续并将handleClick绑定到this 。 首先,我们需要在组件中创建一个constructor函数。 然后,我们将handleClick绑定到this内部。

constructor () {
super()
  this.handleClick = this.handleClick.bind(this)
}

现在,我们的文件应如下所示:

 import React, { Component } from 'react'
import './App.css'
 class App extends Component {
constructor () {
super ()
    this .handleClick = this .handleClick.bind( this )
}
  render () {
return (
<div className='button__container'>
<button className='button' onClick={ this .handleClick}>
Click Me
</button>
</div>
)
}
}
 export default App

最后,我们需要定义我们的handleClick函数。 让我们首先通过单击console.log '成功!',确保一切都正确连接。 单击该按钮时。

handleClick () {
console.log('Success!')
}

这是您的代码现在应该是什么样的:

 import React, { Component } from 'react'
import './App.css'
 class App extends Component {
constructor () {
super ()
     this .handleClick = this .handleClick.bind( this )
}
  handleClick () {
console.log('Success!')
}
  render () {
return (
<div className='button__container'>
<button className='button' onClick={ this .handleClick}>
Click Me
</button>
</div>
)
}
}
 export default App

单击按钮后,您应该在浏览器中看到以下内容:

确保单击按钮时看到“成功!”。 出现在您的控制台中。 如果这样做,则意味着您已正确将handleChange函数连接到该按钮,并且已经准备handleChange ,可以继续本教程的第3部分

From: https://hackernoon.com/tutorial-how-to-make-http-requests-in-react-part-2-4cfdba3ec65

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值