react不需使用jsx吗_开始使用React所需的一切

react不需使用jsx吗

“The hardest thing about getting started, is getting started” - Guy Kawasaki
“入门最难的是入门”-川崎圭(Guy Kawasaki)

React is the most popular Front End Library in use today. But getting started on React can be hard at times. There is Component Hierarchy, states, props and functional programming involved. This article tries to solve this problem, by giving you a nice and easy way of getting started in React. So without wasting any time, let’s jump in.

React是当今使用最流行的前端库。 但是有时候开始使用React可能很困难。 其中涉及组件层次结构,状态,道具和功能编程。 本文试图通过为您提供一种简便易用的React入门方法来解决此问题。 因此,我们不浪费任何时间,让我们进入。

环境 (Environment)

We will use a simple HTML file in this article. Just make sure to include the following script tags in the head section of your HTML file.

在本文中,我们将使用一个简单HTML文件。 只要确保在HTML文件的头部包含以下脚本标记即可。

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script>

So our working file should look like this.

因此,我们的工作文件应如下所示。

<!DOCTYPE html>
<html>
<head>    
    <title>My React App</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script>    
</head>
<body>
    
    <div id="root"></div>

    <script type="text/babel" >   
    
       //React code should go here
    </script>
</body>
</html>
</script></body></html>

We are good to go now.

我们现在走了。

组件 (Components)

Components are the meat and potatoes of a React application.

组件是React应用程序的肉和土豆。

They are independent and reusable blocks of code that build a React application.

它们是构建React应用程序的独立和可重用的代码块。

Let’s look at our first component.

让我们看一下第一个组件。

class App extends React.Component{
 render(){
  return <h3>Hello React World.</h3>
 }
}
ReactDOM.render(            
 <App />,
 document.getElementById('root')
);

Our App component is an ES6 class which extends the Component class of React. It has a single method for now called render, which returns an h3 element returning the text ‘Hello React World’. The browser will only render elements returned by the render() method.

我们的App组件是ES6类,它扩展了React的Component类。 它现在有一个方法叫做render ,它返回一个h3元素,返回文本“ Hello React World”。 浏览器将仅渲染render()方法返回的元素。

但是请稍等,该渲染方法是否必要? (But wait a minute, is that render method necessary?)

Yes, a class component must include a render method. All the other methods are optional.

是的,类组件必须包含render方法。 所有其他方法都是可选的。

ReactDOM.render() is rendering the App component in a div element with the id ‘root’. It takes the component as the first parameter and parent div as the second parameter.

ReactDOM.render()正在使用id为“ root”的div元素呈现App组件。 它将组件作为第一个参数,将父div作为第二个参数。

JavaScript语法扩展(JSX) (JavaScript Syntax Extension (JSX))

The h3 element we declared in the App component is not HTML, it’s JavaScript Syntax Extension (JSX). JSX is a syntax extension in JavaScript. It enables us to write HTML like JavaScript Objects(JSX) in JavaScript.

我们在App组件中声明的h3元素不是HTML,而是JavaScript语法扩展(JSX)。 JSX是JavaScript中的语法扩展。 它使我们能够在JavaScript中编写类似JavaScript Objects(JSX)HTML。

class App extends React.Component{
 render(){
  const element = <h3>Hello React World</h3>;
  return <div>{element}</div>;
 }
}

JSX gives us the power of JavaScript while writing HTML. Those curly braces {} in the example above tell the React compiler that element is a JavaScript variable. Let’s see another more practical example.

JSX在编写HTML时为我们提供了JavaScript的功能。 上例中的花括号{}告诉React编译器该元素是一个JavaScript变量。 让我们来看另一个更实际的例子。

render() {
 const users = [‘Abdul Moiz’,’Linda Lee’,’John Frank’];
 const listItems = users.map(user => <li>{user}</li>);
 return <ul>{listItems}</ul>; 
}

In the example above, we have a list of users in an array that we’ve mapped on the list and made an array of li elements. We’ll use this in our ul element later.

在上面的示例中,我们在数组中有一个用户列表,该用户列表已映射到该列表上,并形成了一个li元素数组。 我们将在我们的ul使用它 元素稍后。

JSX is the recommended way and the industry de facto standard to declare your UI in React.

推荐使用JSX和行业标准来在React中声明您的UI。

道具 (Props)

Props are the properties passed by the parent component to child components.

道具是父组件传递给子组件的属性。

It is a common pattern in React to abstract away the common UI logic in child components. In those cases, it is common for the parent component to pass some data as properties in child components.

在React中,常见的模式是抽象出子组件中的通用UI逻辑。 在这些情况下,父组件通常会将某些数据作为子组件中的属性进行传递。

class App extends React.Component {
 render() {
  return <Greet greeting="Hello" />;  
 }
}
class Greet extends React.Component{
 render(){
  return <h3>{this.props.greeting} World</h3>;
 }
}

In the example above, we have passed a greeting prop to the Greet component and used it in our App component. We can access all the props from the this.props object of our class. In this case, we are accessing greeting as this.props.greeting.

在上面的示例中,我们向Greet组件传递了一个问候道具,并在我们的App组件中使用了它。 我们可以从类的this.props对象访问所有道具。 在这种情况下,我们将访问问候语this.props.greeting

可以,但是我可以传递什么类型的数据呢? (OK, but what type of data can I pass in props?)

Pretty much every default data structure in JavaScript: string literals, numbers, array, objects, and even functions. Yes we can pass functions, but we won’t be getting into that right now.

JavaScript中几乎所有的默认数据结构:字符串文字,数字,数组,对象甚至函数。 是的,我们可以传递函数,但是我们现在不会涉及。

(State)

State, like props, also holds data, but some different types of data.

状态像道具一样,也可以存储数据,但是可以存储一些不同类型的数据。

Props hold the data sent by the parent component. State holds the private, dynamic data of the component. State holds the data which changes between multiple renderings of the component.

道具保存父组件发送的数据。 State拥有组件的私有动态数据。 状态保存在组件的多个渲染之间变化的数据。

Props get passed to the component (like function parameters), whereas state is managed within the component (like variables declared within a function) - React Docs
道具传递给组件(如函数参数),而状态在组件内管理(如函数内声明的变量)-React Docs

Complex? Don’t worry, it will all make sense in a moment.

复杂? 不用担心,片刻后一切都会变得有意义。

class App extends React.Component {
 constructor(){
  super();
  this.state = {name :"Abdul Moiz"};
 }
 changeName(){
  this.setState({name : "John Doe"});
 }
 
 render(){
  return (
   <div>
     <h3>Hello {this.state.name}</h3>
     <button type='button' onClick=this.changeName.bind(this)}>
      Change
     </button>
   </div>
  );
 }
}

As we can see, we have to initialize the state in a constructor and then we can use it in the render method. Like props, we are accessing state with the ‘this.state’ object. And on the click event of our Change button, we are changing the value of name in state to ‘John Doe’.

如我们所见,我们必须在构造函数中初始化状态,然后才能在render方法中使用它。 像道具一样,我们使用'this.state'对象访问状态。 在更改按钮的点击事件中,我们将状态名称的值更改为“ John Doe”。

setState() (setState())

We are using the setState() method to change our state. setState() is available by default in React Component and is the only way to change state. We are passing an object as the parameter to setState(). React will look at the passed object and will change only the provided keys of the state with the provided values.

我们正在使用setState()方法更改状态。 setState()默认在React Component中可用,并且是更改状态的唯一方法。 我们将一个对象作为参数传递给setState() 。 React将查看传递的对象,并将仅使用提供的值更改状态提供的键。

But wait a minute, if setState() is the only way to change the state, does this mean that I cannot change the state straight away?

但是请稍等,如果setState()是更改状态的唯一方法,这是否意味着我不能立即更改状态?

Yes, we cannot change the state straight away like this:

是的,我们不能像这样立即更改状态:

this.state.name = “John Doe”;

Because when we call setState(), it tells React that data has been changed and we need to re-render the component with the updated data. Updating the state straight away will have no effect on UI.

因为当我们调用setState()时 ,它告诉React数据已更改,因此我们需要使用更新后的数据重新呈现组件。 立即更新状态不会对UI产生影响。

事件处理程序 (Event Handlers)

Event handlers in React are not very different from event handlers in the DOM. But they have some small yet important differences.

React中的事件处理程序与DOM中的事件处理程序没有太大区别。 但是它们之间存在一些细微但重要的差异。

In the DOM, event handlers are lowercase, but in React, event handlers are camelCase. Secondly, in the DOM, event handlers take value as a string, but in React, event handlers take function reference as value.

在DOM中,事件处理程序为小写,但在React中,事件处理程序为camelCase。 其次,在DOM中,事件处理程序将value作为字符串,但是在React中,事件处理程序将函数引用作为值。

The following is an example of how we handle an event in the DOM:

以下是我们如何处理DOM中事件的示例:

<button type=”submit” onclick=”doSomething()”></button>

And here’s how it’s done in React:

这是在React中完成的方式:

<button type=”submit” onClick=doSomething></button>

If you notice, in the DOM, we’re handling the click event using the onclick (lowercase) DOM property. While in React, we are using the onClick (camelCase) event handler from React. Also, we are passing a string value doSomething() in the DOM. But in React, we are passing the reference of the function doSomething as the value.

如果您注意到,在DOM中,我们将使用onclick (小写)DOM属性来处理click事件。 在React中,我们使用React的onClick (camelCase)事件处理程序。 另外,我们在DOM中传递字符串值doSomething() 。 但是在React中,我们将函数doSomething的引用作为值传递。

If you want to read about the full list of events provided by React (as usual, there are tons of them), consider reading this article from the official docs.

如果您想了解React提供的事件的完整列表(通常,其中有很多事件),请考虑阅读官方文档中的这篇文章

Tired? Me too, but we are almost there — keep up the learning!

累? 我也是,但是我们快到了-继续学习!

生命周期方法(生命周期挂钩) (Life Cycle Methods (Life Cycle Hooks))

React gives us some special methods called Life Cycle Hooks. These life cycle hooks run at particular times in a the life cycle of a component. Luckily, we can put our own functionality in those life cycle hooks, by overriding them in our component. Let’s look at some of the commonly used life cycle hooks.

React为我们提供了一些称为生命周期挂钩的特殊方法。 这些生命周期挂钩在组件生命周期的特定时间运行。 幸运的是,我们可以通过在我们的组件中覆盖它们来将我们自己的功能放在这些生命周期挂钩中。 让我们看一些常用的生命周期挂钩。

componentDidMount() (componentDidMount())

Mounting is the time when the component gets rendered for the first time in the browser. componentDidMount() runs after the component gets mounted. It is a good place to fetch any data or initiate anything.

挂载是组件在浏览器中首次呈现的时间。 componentDidMount()在组件安装后运行。 这是获取任何数据或启动任何内容的好地方。

componentDidUpdate() (componentDidUpdate())

As its name suggests, componentDidUpdate() runs after the component gets updated. It is the place to handle data changes. Maybe you want to handle some network requests, or perform calculations based on the changed data. componentDidUpdate() is the place to do all of that.

顾名思义, componentDidUpdate()在组件更新后运行。 它是处理数据更改的地方。 也许您想处理一些网络请求,或者根据更改后的数据执行计算。 componentDidUpdate()是执行所有这些操作的地方。

Let’s see that in action:

让我们看看实际情况:

class App extends React.Component {
 constructor(){
  super(); 
  this.state = {
   person : {name : "" , city : ""}
  };
 }
 componentDidMount(){
  //make any ajax request
  this.setState({
   person : {name : "Abdul Moiz",city : "Karachi"}
  });
 }
 componentDidUpdate(){
  //because I could'nt come up with a simpler example of //componentDidUpdate
  console.log('component has been updated',this.state);
 }
 render(){
  return (
   <div>
    <p>Name : {this.state.person.name}</p>
    <p>City : {this.state.person.city}</p>
   </div>
  );
 }
}

Our initial state has two properties, name and city, and both have an empty string as value. In componentDidMount() we set the state and change name to ‘Abdul Moiz’ and city to ‘Karachi’. Because we changed the state, the component updated as a result of executing componentDidUpdate().

我们的初始状态具有两个属性,即name和city,并且都具有一个空字符串作为值。 在componentDidMount() 我们设置州,并将名称更改为“ Abdul Moiz”,将城市更改为“ Karachi”。 因为我们更改了状态,所以组件由于执行componentDidUpdate()而更新。

结论 (Conclusion)

React is here to stay. Learning React can be difficult, but you will love it once you surpass the initial learning curve. This article was meant to make that learning process a little bit easier for you.

React待在这里。 学习React可能很困难,但是一旦您超过了最初的学习曲线,您就会喜欢它。 本文旨在使您的学习过程更加轻松。

And don’t forget to follow me on Twitter.

并且不要忘记在Twitter上关注我。

资源资源 (Resources)

翻译自: https://www.freecodecamp.org/news/everything-you-need-to-know-to-get-started-in-react-11311ae997cb/

react不需使用jsx吗

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值