【八股系列】React中props和state的区别是什么?

Reactpropsstate的区别是:

  1. props是用来从父组件向子组件 进行传递数据的,在子组件中可以用props来接收到父组件传递过来的参数。
  2. props不可变 的,用户不能在子组件中修改props的值,因为从父组件中传递过来的值被认为是不可变数据。
  3. state表示的组件的内部状态 ,是私有数据
  4. state可变 的,用户可以通过setState等来修改数据 ,且React会根据state的修改重新进行组件的渲染。

示例代码:

js 复制代码
// 父组件
class ParentComponent extends React.Component {
  render() {
    return (
      <ChildComponent name="John" age={25} />
    );
  }
}

// 子组件
class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        <p>Name: {this.props.name}</p>
        <p>Age: {this.props.age}</p>
      </div>
    );
  }
}

// 父组件
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
      </div>
    );
  }
}
相关推荐
属于自己的天空17 分钟前
每天省去重复 Prompt:我用 Skills 把 CRUD 生成标准化了
前端·后端
卡卡罗特AI18 分钟前
GitHub怎么用?零基础,保姆级使用教程-上!建议收藏
前端·后端·github
自然 醒20 分钟前
v-tooltip自定义指令封装
前端·javascript·vue.js
因_崔斯汀32 分钟前
Three.js 3D 热力云图效果实现
前端·three.js
mONESY32 分钟前
🎨 从零搭建 React + TypeScript + Vite 项目:以 Color Picker 为例,聊聊前端工程化的 model/api 分层架构
react.js
爱勇宝1 小时前
人到了一定年纪,才会看懂这些人性真相
前端·后端
梓䈑1 小时前
【用 Vibe Coding 实现的 C++17 在线判题系统】前端开发 + Web 自动化测试
前端·c++·ai编程
程序员黑豆2 小时前
鸿蒙应用开发 @BuilderParam 使用教程:实现灵活的 UI 插槽
前端·harmonyos
万少2 小时前
用 TraeWork 给小孩做一个家庭工作台
前端·人工智能·后端