react基础

事件绑定

javascript 复制代码
import React, { Component } from "react";

export default class HandleClick extends Component {
  eventHandle() {
    console.log("这是第二种的");
  }
  eventHandle2=() => console.log("这是第三种的");
  eventHandle3=() => console.log("这是第四种的");
  render() {
    return (
      <div>
        <button
          onClick={() => {
            console.log("这是第一种写法");
          }}
        >
          点击我第一种
        </button>
        <button
          onClick={this.eventHandle}
        >
          点击我第二种
        </button>
        <button
          onClick={this.eventHandle2}
        >
          点击我第三种
        </button>
        <button
          onClick={() =>{this.eventHandle3()}}
        >
          点击我第四种
        </button>
      </div>
    );
  }
}

react并不会真正的绑定事件到每一个具体的元素上,而是采用事件代理的模式

关于富文本编辑器

javascript 复制代码
import React, { Component } from "react";

export default class TodoList extends Component {
  myref = React.createRef();
  handleAdd = () => {
    this.setState({
      list: [
        ...this.state.list,
        {
          id: Math.random() * 100000,
          name: this.myref.current.value,
        },
      ],
    });
    this.myref.current.value = "";
  };
  handleDelete = (id) => {
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };
  state = {
    list: [
      { id: 1, name: "huahua" },
      { id: 2, name: "niu" },
      { id: 3, name: "niu12" },
    ],
  };
  render() {
    return (
      <div>
        <input ref={this.myref}></input>
        <button onClick={this.handleAdd}>添加</button>
        {this.state.list.length !== 0 ? (
          <ul>
            展示
            {this.state.list.map((item) => (
              <li key={item.id}>
                <span
                  dangerouslySetInnerHTML={{
                    __html: item.name,
                  }}
                ></span>
                <button onClick={() => this.handleDelete(item.id)}>删除</button>
              </li>
            ))}
          </ul>
        ) : (
          <div>购物车空空如也</div>
        )}
      </div>
    );
  }
}

关于setState

是异步更新状态的,更新真实dom

多次setState会合并处理,

上面黑色的内容是react17的内容,18及以后都做了修改,不管同步还是异步代码,都是异步执行的

就是在按钮点击的时候,会出现如果多次设置setState,是异步更新状态,并且相同的处理是会进行覆盖的,执行的是最后一次的setState

javascript 复制代码
import React, { Component } from "react";

export default class AddCount extends Component {
  state = {
    count: 0,
  };
  handleAdd = () => {
    console.log("我执行了");

    this.setState({
      count: this.state.count + 1,
    });
    console.log(this.state.count);
    this.setState({
      count: this.state.count + 1,
    });
    console.log(this.state.count);
    this.setState({
      count: this.state.count + 1,
    });
    console.log(this.state.count);
  };
  handleAdd2 = () => {
    setTimeout(() => {
      this.setState({
        count: this.state.count + 1,
      });
      console.log(this.state.count);
      this.setState({
        count: this.state.count + 1,
      });
      console.log(this.state.count);
      this.setState({
        count: this.state.count + 1,
      });
      console.log(this.state.count);
    }, 2000);
  };
  render() {
    return (
      <div>
        <button onClick={this.handleAdd}>{this.state.count}</button>
        <button onClick={this.handleAdd2}>{this.state.count}</button>
      </div>
    );
  }
}

如果想要获取到什么时候改变状态,setState里面第二个参数是一个回调函数,可以获取到的

javascript 复制代码
  handleAdd2 = () => {
    setTimeout(() => {
      this.setState(
        {
          count: this.state.count + 1,
        },
        () => {
          console.log(this.state.count);
        }
      );
      console.log(this.state.count);
      this.setState({
        count: this.state.count + 2,
      });
      console.log(this.state.count);
      this.setState({
        count: this.state.count + 1,
      });
      console.log(this.state.count);
    }, 2000);
  };

setSteate的BetterScroll应用

javascript 复制代码
import React, { Component } from "react";
import axios from "axios";
import BScroll from "@better-scroll/core";
export default class BuyTick extends Component {
  constructor() {
    super();
    axios({
      url: "https://m.maizuo.com/gateway?cityId=110100&ticketFlag=1&k=1429130",
      headers: {
        // 显式将对象转为JSON字符串
        "x-client-info": JSON.stringify({
          a: "3000",
          ch: "1002",
          v: "5.2.1",
          e: "17604099951825893676744705",
          bc: "110100",
        }),
        "x-host": "mall.film-ticket.cinema.list",
      },
      method: "get",
    }).then((res) =>
      this.setState(
        {
          list: res.data.data.cinemas,
          copyList: res.data.data.cinemas,
        },
        () => {
          new BScroll(document.querySelector(".wrapper"));
        }
      )
    );
  }
  state = {
    list: [],
    copyList: [],
  };
  handleInput = (e) => {
    console.log(e.target.value);
    this.setState({
      list: this.state.copyList.filter((item) =>
        item.name.toUpperCase().includes(e.target.value.toUpperCase())
      ),
    });
    console.log("111", this.state.list);
  };
  render() {
    return (
      <div>
        <input onChange={this.handleInput}></input>
        <div
          className="wrapper"
          style={{ height: "300px", backgroundColor: "pink", overflow: 'hidden' }}
        >
          <dl>
            {this.state.list.map((item) => {
              return (
                <div style={{ borderBottom: "1px solid #797373ff" }}>
                  <span style={{ background: "pink" }}>{item.name}</span>
                  <span>{item.address}</span>
                </div>
              );
            })}
          </dl>
        </div>
      </div>
    );
  }
}

props

类组件的写法:

javascript 复制代码
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class NavBar extends Component {
  static propTypes = {
    title: PropTypes.string,
    ifShowRight: PropTypes.bool,
  };
  static defaultProps = {
    ifShowRight: true,
  };
  test = () => {
    console.log(this.props.ifShowRight);
  };
  render() {
    return (
      <div>
        <button>返回</button>
        我是{this.props.title}
        {this.props.ifShowRight && <button>返回</button>}
        {this.test()}
      </div>
    );
  }
}
javascript 复制代码
import React, { Component } from "react";
import NavBar from "../NavBar";
export default class Props extends Component {
  obj1 = {
    a: 1,
    b: 2,
  };
  render() {
    return (
      <div>
        <div>
          <h2>首页</h2>
          {/* 还可以用...obj来写 */}
          <NavBar title="首页" ifShowRight={false} {...this.obj1}></NavBar>
        </div>
        <div>
          <h2>列表</h2>
          <NavBar title="列表"></NavBar>
        </div>
        <div>
          <h2>购物车</h2>
          <NavBar title="购物车"></NavBar>
        </div>
      </div>
    );
  }
}

函数式组件的写法(默认值,类型限制)

javascript 复制代码
import React from "react";

export default function Silder(props) {
  const { bg } = props;
  return (
    <div>
      <ul style={{ background: bg }}>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
      </ul>
    </div>
  );
}
javascript 复制代码
import React from "react";

export default function Silder({ bg = "blue" }) {
  return (
    <div>
      <ul style={{ background: bg }}>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
      </ul>
    </div>
  );
}

受控组件:

关于input原来的写法

javascript 复制代码
import React, { Component } from "react";
import axios from "axios";
import BScroll from "@better-scroll/core";
export default class BuyTick extends Component {
  constructor() {
    super();
    axios({
      url: "https://m.maizuo.com/gateway?cityId=110100&ticketFlag=1&k=1429130",
      headers: {
        // 显式将对象转为JSON字符串
        "x-client-info": JSON.stringify({
          a: "3000",
          ch: "1002",
          v: "5.2.1",
          e: "17604099951825893676744705",
          bc: "110100",
        }),
        "x-host": "mall.film-ticket.cinema.list",
      },
      method: "get",
    }).then((res) =>
      this.setState(
        {
          list: res.data.data.cinemas,
          copyList: res.data.data.cinemas,
        },
        () => {
          new BScroll(document.querySelector(".wrapper"));
        }
      )
    );
  }
  state = {
    list: [],
    copyList: [],
  };
  handleInput = (e) => {
    console.log(e.target.value);
    this.setState({
      list: this.state.copyList.filter((item) =>
        item.name.toUpperCase().includes(e.target.value.toUpperCase())
      ),
    });
    console.log("111", this.state.list);
  };
  render() {
    return (
      <div>
        <input onChange={this.handleInput}></input>
        <div
          className="wrapper"
          style={{ height: "300px", backgroundColor: "pink", overflow: 'hidden' }}
        >
          <dl>
            {this.state.list.map((item) => {
              return (
                <div style={{ borderBottom: "1px solid #797373ff" }}>
                  <span style={{ background: "pink" }}>{item.name}</span>
                  <span>{item.address}</span>
                </div>
              );
            })}
          </dl>
        </div>
      </div>
    );
  }
}

这个主要是通过去更改setState去变化,如果用受控榜单绑定的话

javascript 复制代码
import React, { Component } from "react";
import axios from "axios";
import BScroll from "@better-scroll/core";
export default class BuyTick extends Component {
  constructor() {
    super();
    axios({
      url: "https://m.maizuo.com/gateway?cityId=110100&ticketFlag=1&k=1429130",
      headers: {
        // 显式将对象转为JSON字符串
        "x-client-info": JSON.stringify({
          a: "3000",
          ch: "1002",
          v: "5.2.1",
          e: "17604099951825893676744705",
          bc: "110100",
        }),
        "x-host": "mall.film-ticket.cinema.list",
      },
      method: "get",
    }).then((res) =>
      this.setState(
        {
          list: res.data.data.cinemas,
        },
        () => {
          new BScroll(document.querySelector(".wrapper"));
        }
      )
    );
  }
  state = {
    list: [],
    key: "",
  };
  // handleInput = (e) => {
  //   console.log(e.target.value);
  //   this.setState({
  //     list: this.state.copyList.filter((item) =>
  //       item.name.toUpperCase().includes(e.target.value.toUpperCase())
  //     ),
  //   });
  //   console.log("111", this.state.list);
  // };
  handleQuery = () => {
    return this.state.list.filter((item) =>
      item.name.toUpperCase().includes(this.state.key)
    );
  };
  render() {
    return (
      <div>
        <input
          value={this.state.key}
          onChange={(evt) => {
            this.setState({ key: evt.target.value });
          }}
        ></input>
        <div
          className="wrapper"
          style={{
            height: "300px",
            backgroundColor: "pink",
            overflow: "hidden",
          }}
        >
          <dl>
            {this.handleQuery().map((item) => {
              return (
                <div style={{ borderBottom: "1px solid #797373ff" }}>
                  <span style={{ background: "pink" }}>{item.name}</span>
                  <span>{item.address}</span>
                </div>
              );
            })}
          </dl>
        </div>
      </div>
    );
  }
}

通信:子传父

javascript 复制代码
import React, { Component } from "react";

function SonA({ handleShow }) {
  return <button onClick={handleShow}>点击我</button>;
}
function SonB() {
  return (
    <div
      style={{ width: "200px", height: "200px", backgroundColor: "pink" }}
    ></div>
  );
}
export default class Tongxin extends Component {
  state = {
    isShow: false,
  };
  handleIfShow=() => {
    this.setState({ isShow: !this.state.isShow });
  }
  render() {
    return (
      <div>
        <SonA handleShow={this.handleIfShow}></SonA>
        {this.state.isShow && <SonB></SonB>}
      </div>
    );
  }
}

通信:表单域通信

javascript 复制代码
import React, { Component } from "react";
function InputSon({ text, label, value, handleInput }) {
  return (
    <div>
      <label>{label}</label>{" "}
      <input
        type={text}
        value={value}
        onChange={(e) => handleInput(e.target.value)}
      ></input>
    </div>
  );
}
export default class Biaodan extends Component {
  state = {
    username: "",
    password: "",
  };
  render() {
    return (
      <div>
        <InputSon
          text="text"
          label="用户名"
          value={this.state.username}
          handleInput={(value) => this.setState({ username: value })}
        ></InputSon>
        <InputSon
          text="password"
          label="密码"
          value={this.state.password}
          handleInput={(value) => this.setState({ password: value })}
        ></InputSon>
        <button onClick={() => this.setState({ username: "", password: "" })}>
          重置
        </button>
      </div>
    );
  }
}

ref的表单域通信

javascript 复制代码
import React, { Component, useImperativeHandle, useState,  } from "react";
function InputSon({ text, label,ref }) {
  const [value, setValue] = useState("");
  const clear = () => {
    setValue("");
  };
  useImperativeHandle(ref, () => ({
    clear: clear,
  }));
  return (
    <div>
      <label>{label}</label>
      <input
        type={text}
        value={value}
        onChange={(e) => setValue(e.target.value)}
      ></input>
    </div>
  );
}
export default class Biaodan extends Component {
  username = React.createRef();
  password = React.createRef();
  render() {
    return (
      <div>
        <InputSon text="text" label="用户名" ref={this.username}></InputSon>
        <InputSon text="password" label="密码" ref={this.password}></InputSon>
        <button
          onClick={() => {
            this.username.current.clear();
            this.password.current.clear();
          }}
        >
          重置
        </button>
      </div>
    );
  }
}
相关推荐
浪裡遊4 小时前
MUI组件库与主题系统全面指南
开发语言·前端·javascript·vue.js·react.js·前端框架·node.js
DiXinWang4 小时前
关闭谷歌浏览器提示“若要接收后续 Google Chrome 更新,您需使用 Windows 10 或更高版本”的方法
前端·chrome
CoderYanger4 小时前
前端基础——HTML练习项目:填写简历信息
前端·css·职场和发展·html
muyouking114 小时前
深入理解 HTML `<label>` 的 `for` 属性:提升表单可访问性与用户体验
前端·html·ux
软件技术NINI4 小时前
html css js网页制作成品——饮料官网html+css+js 4页网页设计(4页)附源码
javascript·css·html
软件技术NINI4 小时前
html css js网页制作成品——HTML+CSS辣条俱乐部网页设计(5页)附源码
javascript·css·html
IT_陈寒5 小时前
Java性能调优:从GC日志分析到实战优化的5个关键技巧,让你的应用快如闪电!
前端·人工智能·后端
Mintopia5 小时前
🚀 Next.js API 压力测试:一场前端与后端的“极限拉扯”
前端·后端·全栈
Mintopia5 小时前
🛡️ 对抗性攻击与防御:WebAI模型的安全加固技术
前端·javascript·aigc