返回

父子组件原始通信:掌握最基本的props

前端

父传子:props的使用

父组件通过给子组件标签里边绑定:<属性名>="<要传的值>" 这个表达式,即可实现父组件向子组件传递数据。例如:

// 父组件
class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child name="John Doe" />
      </div>
    );
  }
}

// 子组件
class Child extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}!</h1>
      </div>
    );
  }
}

在上面的例子中,父组件<Parent>通过<Child>标签的<name>属性向子组件<Child>传递了"John Doe"这个值。子组件<Child>通过this.props.name访问这个值,并将其显示在页面上。

子传父:父组件提供的函数

在某些情况下,子组件需要将数据或事件通知给父组件。这时,父组件可以通过向子组件提供函数来实现这种通信。例如:

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

  handleButtonClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <Child onButtonClick={this.handleButtonClick} />
        <h1>Count: {this.state.count}</h1>
      </div>
    );
  }
}

// 子组件
class Child extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.onButtonClick}>Click me!</button>
      </div>
    );
  }
}

在上面的例子中,父组件<Parent>通过<Child>标签的<onButtonClick>属性向子组件<Child>提供了handleButtonClick函数。子组件<Child>通过<button>元素的<onClick>事件监听器调用这个函数,从而通知父组件<Parent>发生了点击事件。父组件<Parent>在收到这个事件通知后,更新了内部状态count的值,并将其显示在页面上。

总结

父子组件通信是React中非常重要的一个概念。通过props和父组件提供的函数,我们可以实现父子组件之间的数据传递和事件通知。掌握了这些基本知识,我们就可以构建出更加复杂和交互性更强的React应用程序。