Skip to content
分类目录:

react组件与父子组件通讯

Post date:
Author:
Number of comments: no comments

react组件与父子组件通讯,实现了父级通过props传值给子组件,子组件通过props触发父组件方法。

react组件与父子组件通讯

子组件:component1.js


import React from "react";
import PropeTyps from "prop-types";

export default class Component1 extends React.Component {
  state = {
    uname: "cyy",
  };

  change(e) {
    this.setState({
      uname: e.target.value,
    });
  }

  getUname = () => {
    this.props.getUname(this.state.uname);
  };

  render() {
    return (
      <div>
        姓名: {this.props.name}, 年龄: {this.props.age}
        <input
          value={this.state.uname}
          onChange={(event) => {
            this.change(event);
          }}
        ></input>
        <button onClick={() => this.getUname()}>触发父级事件</button>
      </div>
    );
  }
}

Component1.PropeTyps = {
  name: PropeTyps.string,
  age: PropeTyps.number,
};

// 默认的值
Component1.defaultProps = {
  name: "yyc",
};

父组件:

import React from "react";
import "./index.less";
import Component1 from "./components/component1";

/**
 * 测试用
 */
class Hello extends React.PureComponent {
  state = {
  };
  getUname = (e) => {
    console.log("这里是父级", e);
  };
  render() {
    return (
      <div className="app-container">
        <Component1 name={"cyy"} age={18} getUname={this.getUname}></Component1>
      </div>
    );
  }
}

export default Hello;

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注