umi搭建react+antd项目(六)父子组件通讯

上一篇写了一个子组件,只是把值传入进来,这篇讲解在子组件修改父组件的数据

1.在index.js里,新增方法:updateImg 用于修改list集合

  updateImg() {
    this.setState({
      list: [
        {
          "src": "http://dummyimage.com/468x60"
        }
      ]
    });
  }

在子组件上传入该方法:


完整代码:

import React, {Component} from 'react';
import Link from 'umi/link';
import instance from '../conf/axiosConf';
import ListComponent from '../component/list'

export default class index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: []
    }
  }

  componentDidMount() {
    instance.get("api/img").then(data => {
      this.setState({list: data.list});
    })
  }

  updateImg() {
    this.setState({
      list: [
        {
          "src": "http://dummyimage.com/468x60"
        }
      ]
    });
  }

  render() {
    return (
      
index { this.state.list.map((entry, index) =>
{entry.src}
) }
) } }

2.修改子组件

import React, {Component} from 'react';

export default class List extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      
{ this.props.list.map((entry, index) =>
{entry.src}
) }
) } }

 

你可能感兴趣的:(web前端,react)