React基本内容学习详细教程(1)

超、凢脫俗 2023-10-10 23:59 113阅读 0赞

1.搭建react项目

React安装详细教程
IntelliJIDEA的搭建React项目详细教程

1)项目的目录结构

  1. my-app/
  2. README.md
  3. node_modules/
  4. package.json
  5. .gitignore
  6. public/
  7. favicon.ico
  8. index.html
  9. manifest.json
  10. src/
  11. App.css
  12. App.js
  13. App.test.js
  14. index.css
  15. index.js
  16. logo.svg

2)manifest.json 指定了开始页面 index.html

  1. import logo from './logo.svg';
  2. import './App.css';
  3. function App() {
  4. return (
  5. <div className="App">
  6. <header className="App-header">
  7. <img src={
  8. logo} className="App-logo" alt="logo" />
  9. <p>
  10. 学习react
  11. </p>
  12. <p className="App-link">
  13. how to learn react
  14. </p>
  15. </header>
  16. </div>
  17. );
  18. }
  19. export default App;

3)src/index.js 修改

src/index.js 是一个入口文件,我们可以尝试直接修改 src/index.js 文件代码:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Hello(props) {
  4. return <h1>Hello World!</h1>;
  5. }
  6. ReactDOM.render(<Hello />, document.getElementById('root'));

在这里插入图片描述

2. 详细内容

1)React 元素渲染

在index.html添加元素,将元素渲染到 DOM 中

  1. <div id="example"></div>

在这里插入图片描述
在此 div 中的所有内容都将由 React DOM 来管理,所以我们将其称为 “根” DOM 节点。

我们用 React 开发应用时一般只会定义一个根节点。但如果你是在一个已有的项目当中引入 React 的话,你可能会需要在不同的部分单独定义 React 根节点。

要将React元素渲染到根DOM节点中,我们通过把它们都传递给 ReactDOM.render() 的方法来将其渲染到页面上:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Hello(props){
  4. return <h1> hello world</h1>
  5. }
  6. ReactDOM.render(<Hello/>,document.getElementById('root'));
  7. const element=<h1>hello,react</h1>
  8. ReactDOM.render(
  9. element,
  10. document.getElementById('example')
  11. )

在这里插入图片描述

2) 更新元素渲染

React 元素都是不可变的。当元素被创建之后,你是无法改变其内容或属性的。

目前更新界面的唯一办法是创建一个新的元素,然后将它传入 ReactDOM.render() 方法:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Hello(props){
  4. return <h1> hello world</h1>
  5. }
  6. ReactDOM.render(<Hello/>,document.getElementById('root'));
  7. const element=<h1>hello,react</h1>
  8. ReactDOM.render(
  9. element,
  10. document.getElementById('example')
  11. )
  12. function tick(){
  13. const element=(
  14. <div>
  15. <h1>time show</h1>
  16. <h2> now time is {
  17. new Date().toLocaleTimeString()}</h2>
  18. </div>
  19. );
  20. ReactDOM.render(element,document.getElementById('example'));
  21. }
  22. setInterval(tick,1000);//setInterval() 方法,每秒钟调用一次 ReactDOM.render()

在这里插入图片描述
将要展示的部分封装起来

  1. function Clock(props){
  2. return (
  3. <div>
  4. <div>
  5. <h1>time show</h1>
  6. <h2> now time is {
  7. props.date.toLocaleTimeString()}</h2>
  8. </div>
  9. </div>
  10. )
  11. }
  12. function tick(){
  13. ReactDOM.render(<Clock date={
  14. new Date()}/>,document.getElementById('example'));
  15. }
  16. setInterval(tick,1000);

创建一个 React.Component 的 ES6 类,该类封装了要展示的元素,需要注意的是在 render() 方法中,需要使用 this.props替换 props

  1. class Clock extends React.component{
  2. return (){
  3. return(
  4. <div>
  5. <div>
  6. <h1>time show</h1>
  7. <h2> now time is {
  8. this.props.toLocaleTimeString()}</h2>
  9. </div>
  10. </div>
  11. );
  12. }
  13. }
  14. function tick(){
  15. ReactDOM.render(<Clock date={
  16. new Date()}/>,document.getElementById('example'));
  17. }
  18. setInterval(tick,1000);

3) React JSX

  • JSX 是一个看起来很像 XML 的 JavaScript 语法扩展。
  • 优点:

    • JSX 执行更快,因为它在编译为 JavaScript 代码后进行了优化。
    • 它是类型安全的,在编译过程中就能发现错误。
    • 使用 JSX 编写模板更加简单快速。

    const element =

    Hello, world!

    ;

  • 它被称为 JSX, 一种 JavaScript 的语法扩展

  • React 中使用 JSX 来描述用户界面。
  • JSX 是在 JavaScript 内部实现的。
  • 元素是构成 React 应用的最小单位,JSX 就是用来声明 React 当中的元素。
  • 与浏览器的 DOM 元素不同,React 当中的元素事实上是普通的对象React DOM 可以确保 浏览器 DOM 的数据内容与 React 元素保持一致
  • 要将 React 元素渲染到根 DOM 节点中,我们通过把它们都传递给ReactDOM.render()的方法来将其渲染到页面

index.html 添加元素
在这里插入图片描述

index.js

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. const element=<h1>hello,react</h1>
  4. ReactDOM.render(
  5. element,
  6. document.getElementById('example')

在这里插入图片描述

(1)使用 JSX

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta name="theme-color" content="#000000" />
  7. <title>React App</title>
  8. </head>
  9. <body>
  10. <div id="example"></div>
  11. </body>
  12. </html>
  13. import React from 'react';
  14. import ReactDOM from 'react-dom';
  15. ReactDOM.render(
  16. <h1>{
  17. 1+1}</h1>,
  18. document.getElementById('example')
  19. )

在这里插入图片描述

(2)JavaScript 表达式

在 JSX 中不能使用 if else 语句,但可以使用 conditional (三元运算) 表达式来替代。以下实例中如果变量 i 等于 1 浏览器将输出 true, 如果修改 i 的值,则会输出 false.

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. var i=1;
  4. ReactDOM.render(
  5. <div>
  6. <h1>{
  7. i == 1 ? 'True!' : 'False'}</h1>
  8. </div>
  9. ,
  10. document.getElementById('example')
  11. );

在这里插入图片描述

(3)样式

React 推荐使用内联样式。我们可以使用 camelCase 语法来设置内联样式. React 会在指定元素数字后自动添加 px

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. var i=1;
  4. var style ={
  5. fontSize:100,
  6. color: '#FF0000'
  7. };
  8. ReactDOM.render(
  9. <div>
  10. <h1 style={
  11. style}>{
  12. i == 1 ? 'True!' : 'False'}</h1>
  13. </div>
  14. ,
  15. document.getElementById('example')
  16. );

在这里插入图片描述

(3)注释

注释需要写在花括号中

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. var i=1;
  4. var style ={
  5. fontSize:100,
  6. color: '#FF0000'
  7. };
  8. ReactDOM.render(
  9. <div>
  10. <h1 style={
  11. style}>{
  12. i == 1 ? 'True!' : 'False'}</h1>
  13. {
  14. /* note style*/}
  15. </div>
  16. ,
  17. document.getElementById('example')
  18. );

在这里插入图片描述

(4)数组

JSX 允许在模板中插入数组,数组会自动展开所有成员

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. var i=[
  4. <h1>1</h1>,
  5. <h1>4</h1>,
  6. ];
  7. var style ={
  8. fontSize:50,
  9. color: '#FF0000'
  10. };
  11. ReactDOM.render(
  12. <div>
  13. <div style={
  14. style}>{
  15. i}</div>
  16. {
  17. /* note style*/}
  18. </div>
  19. ,
  20. document.getElementById('example')
  21. );

在这里插入图片描述

4)React 组件

(1)React 组件

  1. function Hello(pros){
  2. return <h1 style={
  3. style}>hello,react</h1>
  4. }

也可以使用 ES6 class 来定义一个组件:

  1. class Welcome extends React.Component{
  2. function Hello(pros){
  3. return <h1 style={
  4. style}>hello,react</h1>
  5. }
  6. }

注意,原生 HTML 元素名以小写字母开头,而自定义的 React 类名以大写字母开头,比如 Hello不能写成 hello。除此之外还需要注意组件类只能包含一个顶层标签,否则也会报错。

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Hello(pros){
  4. return <h1 style={
  5. style}>hello,react</h1>
  6. }
  7. var style ={
  8. fontSize:50,
  9. color: '#FF0000'
  10. };
  11. const ele= <Hello />;
  12. ReactDOM.render(
  13. ele,
  14. document.getElementById('example')
  15. );

在这里插入图片描述

如果我们需要向组件传递参数,可以使用 this.props 对象

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Hello(pros){
  4. return <h1 style={
  5. style}>hello,{
  6. pros.name}</h1>
  7. }
  8. var style ={
  9. fontSize:50,
  10. color: '#FF0000'
  11. };
  12. const ele= <Hello name="java"/>;
  13. ReactDOM.render(
  14. ele,
  15. document.getElementById('example')
  16. );

在这里插入图片描述

(2)复合组件

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Name(pros){
  4. return <h1 style={
  5. style}>hello,{
  6. pros.name}</h1>
  7. }
  8. function Age(pros){
  9. return <h1 style={
  10. style}>hello,{
  11. pros.age}</h1>
  12. }
  13. function Job(pros){
  14. return <h1 style={
  15. style}>hello,{
  16. pros.job}</h1>
  17. }
  18. var style ={
  19. fontSize:50,
  20. color: '#FF0000'
  21. };
  22. function Result(){
  23. return (
  24. <div>
  25. <Name name={
  26. "Amy"}></Name>
  27. <Age age={
  28. 10}></Age>
  29. <Job job={
  30. "student"}></Job>
  31. </div>
  32. )
  33. }
  34. ReactDOM.render(
  35. <Result />,
  36. document.getElementById('example')
  37. );

在这里插入图片描述

5)React State(状态)

React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。

React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)

在 render() 方法中使用 this.state 来修改当前的时间。

添加一个类构造函数来初始化状态 this.state,类组件应始终使用 props 调用基础构造函数。

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. class Clock extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. date: new Date()};
  8. }
  9. render() {
  10. return (
  11. <div style={
  12. style}>
  13. <h1 >Hello, world!</h1>
  14. <h2 >现在是 {
  15. this.state.date.toLocaleTimeString()}.</h2>
  16. </div>
  17. );
  18. }
  19. }
  20. var style ={
  21. fontSize:50,
  22. color: '#FF0000'
  23. };
  24. ReactDOM.render(
  25. <Clock/>,
  26. document.getElementById('example')
  27. );

在这里插入图片描述

(1)将生命周期方法添加到类中

以上代码只显示一次,如何让计时器每秒更新一次

将生命周期方法添加到类中
在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。
每当 Clock 组件第一次加载到 DOM 中的时候,我们都想生成定时器,这在 React 中被称为挂载
同样,每当 Clock 生成的这个 DOM 被移除的时候,我们也会想要清除定时器,这在React 中被称为卸载

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. class Clock extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. date: new Date()};
  8. }
  9. componentDidMount() {
  10. this.timerID = setInterval(
  11. ()=>this.tick(),
  12. 1000
  13. );
  14. }
  15. componentWillUnmount() {
  16. clearInterval(this.timerID);
  17. }
  18. tick(){
  19. this.setState({
  20. date: new Date()
  21. });
  22. }
  23. render() {
  24. return (
  25. <div style={
  26. style}>
  27. <h1 >Hello, world!</h1>
  28. <h2 >现在是 {
  29. this.state.date.toLocaleTimeString()}.</h2>
  30. </div>
  31. );
  32. }
  33. }
  34. var style ={
  35. fontSize:50,
  36. color: '#FF0000'
  37. };
  38. ReactDOM.render(
  39. <Clock/>,
  40. document.getElementById('example')
  41. );

在这里插入图片描述

componentDidMount() 与 componentWillUnmount() 方法被称作生命周期钩子。
在组件输出到 DOM 后会执行 componentDidMount() 钩子,我们就可以在这个钩子上设置一个定时器。
this.timerID 为定时器的 ID,我们可以在 componentWillUnmount() 钩子中卸载定时器。
代码执行顺序:
当 被传递给ReactDOM.render()时,React 调用 Clock 组件的构造函数。 由于 Clock 需要显示当前时间,所以使用包含当前时间的对象来初始化 this.state 。 我们稍后会更新此状态。
React 然后调用 Clock 组件的render() 方法。这是 React 了解屏幕上应该显示什么内容,然后 React 更新 DOM 以匹配 Clock 的渲染输出。
当 Clock 的输出插入到 DOM 中时,React 调用componentDidMount()生命周期钩子。 在其中,Clock 组件要求浏览器设置一个定时器,每秒钟调用一次 tick()
浏览器每秒钟调用 tick() 方法。 在其中,Clock 组件通过使用包含当前时间的对象调用 setState()来调度UI更新。 通过调用 setState() ,React 知道状态已经改变,并再次调用render()方法来确定屏幕上应当显示什么。 这一次,render() 方法中的 this.state.date 将不同,所以渲染输出将包含更新的时间,并相应地更新 DOM。
一旦 Clock 组件被从 DOM 中移除,React 会调用 componentWillUnmount()这个钩子函数,定时器也就会被清除。

(2)数据自顶向下流动

父组件或子组件都不能知道某个组件是有状态还是无状态,并且它们不应该关心某组件是被定义为一个函数还是一个类。
这就是为什么状态通常被称为局部或封装。 除了拥有并设置它的组件外,其它组件不可访问。

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function NowTime(props) {
  4. return <h2>现在是 {
  5. props.date.toLocaleTimeString()}.</h2>;
  6. }
  7. class Clock extends React.Component {
  8. constructor(props) {
  9. super(props);
  10. this.state = {
  11. date: new Date()};
  12. }
  13. componentDidMount() {
  14. this.timerID = setInterval(
  15. ()=>this.tick(),
  16. 1000
  17. );
  18. }
  19. componentWillUnmount() {
  20. clearInterval(this.timerID);
  21. }
  22. tick(){
  23. this.setState({
  24. date: new Date()
  25. });
  26. }
  27. render() {
  28. return (
  29. <div style={
  30. style}>
  31. <h1 >Hello, world!</h1>
  32. <NowTime date={
  33. this.state.date}/>
  34. </div>
  35. );
  36. }
  37. }
  38. var style ={
  39. fontSize:50,
  40. color: '#FF0000'
  41. };
  42. ReactDOM.render(
  43. <Clock/>,
  44. document.getElementById('example')
  45. );

在这里插入图片描述
这通常被称为自顶向下或单向数据流。 任何状态始终由某些特定组件所有,并且从该状态导出的任何数据或 UI 只能影响树中下方的组件。

如果你想象一个组件树作为属性的瀑布,每个组件的状态就像一个额外的水源,它连接在一个任意点,但也流下来。

为了表明所有组件都是真正隔离的,我们可以创建一个 App 组件,它渲染三个Clock:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function NowTime(props) {
  4. return <h2>现在是 {
  5. props.date.toLocaleTimeString()}.</h2>;
  6. }
  7. class Clock extends React.Component {
  8. constructor(props) {
  9. super(props);
  10. this.state = {
  11. date: new Date()};
  12. }
  13. componentDidMount() {
  14. this.timerID = setInterval(
  15. ()=>this.tick(),
  16. 1000
  17. );
  18. }
  19. componentWillUnmount() {
  20. clearInterval(this.timerID);
  21. }
  22. tick(){
  23. this.setState({
  24. date: new Date()
  25. });
  26. }
  27. render() {
  28. return (
  29. <div style={
  30. style}>
  31. <h1 >Hello, world!</h1>
  32. <NowTime date={
  33. this.state.date}/>
  34. </div>
  35. );
  36. }
  37. }
  38. var style ={
  39. fontSize:20,
  40. color: '#FF0000'
  41. };
  42. function Many(){
  43. return(
  44. <div>
  45. <Clock />
  46. <Clock />
  47. <Clock />
  48. </div>
  49. )
  50. }
  51. ReactDOM.render(
  52. <Many/>,
  53. document.getElementById('example')
  54. );

在这里插入图片描述

6)React Props

stateprops主要的区别在于props 是不可变的,而state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义state 来更新和修改数据。 而子组件只能通过 props 来传递数据

(1)使用 Props

name 属性通过 props.name 来获取。

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. function Hello(props) {
  4. return <h2 style={
  5. style}>hello,{
  6. props.name}</h2>;
  7. }
  8. const ele = <Hello name="java" />
  9. var style ={
  10. fontSize:50,
  11. color: '#FF0000'
  12. };
  13. ReactDOM.render(
  14. ele,
  15. document.getElementById('example')
  16. );

在这里插入图片描述

(2) 默认 Props

通过组件类的 defaultProps 属性为 props 设置默认值

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. class Hello extends React.Component {
  4. render() {
  5. return (
  6. <h1 style={
  7. style}>Hello, {
  8. this.props.name}</h1>
  9. );
  10. }
  11. }
  12. Hello.defaultProps = {
  13. name : 'react'
  14. };
  15. const ele = <Hello/>;
  16. var style ={
  17. fontSize:50,
  18. color: '#FF0000'
  19. };
  20. ReactDOM.render(
  21. ele,
  22. document.getElementById('example')
  23. );

在这里插入图片描述

(3)State 和 Props

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. class Hello extends React.Component {
  4. constructor(){
  5. super();
  6. this.state={
  7. name:"pig",
  8. age:"2"
  9. }
  10. }
  11. render() {
  12. return (
  13. <div>
  14. <Name name={
  15. this.state.name}/>
  16. <Age age={
  17. this.state.age}/>
  18. </div>
  19. );
  20. }
  21. }
  22. class Name extends React.Component{
  23. render() {
  24. return(
  25. <h1>Hello, {
  26. this.props.name}</h1>
  27. );
  28. }
  29. }
  30. class Age extends React.Component{
  31. render() {
  32. return(
  33. <h1>It is {
  34. this.props.age} years old</h1>
  35. );
  36. }
  37. }
  38. ReactDOM.render(
  39. <Hello />,
  40. document.getElementById('example')
  41. );

在这里插入图片描述

(4)Props 验证

Props 验证使用 propTypes,它可以保证我们的应用组件被正确使用,React.PropTypes 提供很多验证器 (validator) 来验证传入数据是否有效。当向 props 传入无效数据时,JavaScript 控制台会抛出警告。

以下实例创建一个 Mytitle 组件,属性 title 是必须的且是字符串,非字符串类型会自动转换为字符串 :

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import PropTypes from 'prop-types';
  4. class Name extends React.Component{
  5. render() {
  6. return(
  7. <h1>Hello, {
  8. this.props.name}</h1>
  9. );
  10. }
  11. }
  12. Name.prototypes = {
  13. name: PropTypes.string
  14. }
  15. ReactDOM.render(
  16. <Name name='java' />,
  17. document.getElementById('example')
  18. );

发表评论

表情:
评论列表 (有 0 条评论,113人围观)

还没有评论,来说两句吧...

相关阅读