在React 中,state和props区别是什么?

2023-09-15  本文已影响0人  祈澈菇凉

在 React 中,props 和 state 是两个核心概念,用于管理组件的数据和状态。

Props(属性):

例如:

function ParentComponent() {
  const name = "John";
  return <ChildComponent name={name} />;
}

function ChildComponent(props) {
  return <p>Hello, {props.name}!</p>;
}

在上述示例中,ParentComponent 将名为 "John" 的值通过 name 属性传递给了 ChildComponent,ChildComponent 使用 props.name 来显示该值。

State(状态):

例如:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  handleClick() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.handleClick()}>Increment</button>
      </div>
    );
  }
}

以上的示例中,MyComponent组件内部有一个count的状态,通过 this.state.count来访问它。当按钮点击时,handleClick 方法会调用setState方法来更新 count的值,并触发组件的重新渲染。

总结:

上一篇 下一篇

猜你喜欢

热点阅读