本文共 2715 字,大约阅读时间需要 9 分钟。
构建一个react项目
In this short tutorial we’ll build a very simple example of a counter in React, applying many of the concepts and theory outlined before.
在这个简短的教程中,我们将使用之前概述的许多概念和理论构建一个非常简单的React计数器示例。
Let’s use Codepen for this. We start by forking the .
让我们为此使用Codepen。 我们首先分叉 。
In Codepen we don’t need to import React and ReactDOM as they are already added in the scope.
在Codepen中,我们不需要导入React和ReactDOM,因为它们已经在范围中添加了。
We show the count in a div, and we add a few buttons to increment this count:
我们以div为单位显示计数,并添加一些按钮以增加该计数:
const Button = ({ increment }) => { return }const App = () => { let count = 0 return ({count})}ReactDOM.render(, document.getElementById('app'))
Let’s add the functionality that lets us change the count by clicking the buttons, by adding a onClickFunction
prop:
让我们添加一些功能,通过单击按钮,添加onClickFunction
来更改计数:
const Button = ({ increment, onClickFunction }) => { const handleClick = () => { onClickFunction(increment) } return }const App = () => { let count = 0 const incrementCount = increment => { //TODO } return ({count})}ReactDOM.render(, document.getElementById('app'))
Here, every Button element has 2 props: increment
and onClickFunction
. We create 4 different buttons, with 4 increment values: 1, 10 100, 1000.
在这里,每个Button元素都有两个道具: increment
和onClickFunction
。 我们创建4个不同的按钮,并带有4个增量值:1、10 100、1000。
When the button in the Button component is clicked, the incrementCount
function is called.
单击“按钮”组件中的按钮时,将调用incrementCount
函数。
This function must increment the local count. How can we do so? We can use hooks:
此功能必须增加本地计数。 我们该怎么做? 我们可以使用钩子:
const { useState } = Reactconst Button = ({ increment, onClickFunction }) => { const handleClick = () => { onClickFunction(increment) } return }const App = () => { const [count, setCount] = useState(0) const incrementCount = increment => { setCount(count + increment) } return ({count})}ReactDOM.render(, document.getElementById('app'))
useState()
initializes the count variable at 0 and provides us the setCount()
method to update its value.
useState()
将count变量初始化为0,并向我们提供setCount()
方法以更新其值。
We use both in the incrementCount()
method implementation, which calls setCount()
updating the value to the existing value of count
, plus the increment passed by each Button component.
我们在incrementCount()
方法实现中都使用了这两种方法,该方法调用setCount()
将值更新为count
的现有值,再加上每个Button组件传递的增量。
The complete example code can be seen at
完整的示例代码可以在
翻译自:
构建一个react项目
转载地址:http://ttqgb.baihongyu.com/