Skip to content

React 父子组件通讯

组件使用

  • props 传递数据
  • props 传递函数
  • props 类型检查

父子组件例子

注意状态数据提升,父组件负责管理数据状态和数据拼接

js
import React from 'react';
import PropTypes from 'prop-types';

// 子组件
class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '',
    };
  }

  render() {
    return (
      <div>
        <input value={this.state.title} onChange={this.onTitleChange} />
        <button onClick={this.onSubmit}>提交</button>
      </div>
    );
  }

  onTitleChange = (e) => {
    this.setState({
      title: e.target.value,
    });
  };
  onSubmit = (e) => {
    // 子组件接收函数
    const { submitTitle } = this.props;
    submitTitle(this.state.title);

    this.setState({
      title: '',
    });
  };
}

// props 类型检查
Input.propTypes = {
  submitTitle: PropTypes.func.isRequired,
};

// 子组件
class List extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    // 子组件接收参数
    const { list } = this.props;

    return (
      <ul>
        {list.map((item, index) => {
          return (
            <li key={item.id}>
              <span>{item.title}</span>
            </li>
          );
        })}
      </ul>
    );
  }
}

// props 类型检查
List.propTypes = {
  list: PropTypes.arrayOf(PropTypes.object).isRequired,
};

// 父组件
class TodoListDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [
        {
          id: 'id-1',
          title: '标题1',
        },
        {
          id: 'id-2',
          title: '标题2',
        },
        {
          id: 'id-3',
          title: '标题3',
        },
      ],
    };
  }

  render() {
    return (
      <div>
        {/*父组件传递函数*/}
        <Input submitTitle={this.onSubmitTitle}></Input>
        {/*父组件传递参数*/}
        <List list={this.state.list}></List>
      </div>
    );
  }

  onSubmitTitle = (title) => {
    this.setState({
      list: this.state.list.concat({
        id: `id-${Date.now()}`,
        title,
      }),
    });
  };
}

export default TodoListDemo;

基于 MIT 许可发布