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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26744901/article/details/84066033

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

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

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

在子组件上传入该方法:

<ListComponent updateImg={this.updateImg.bind(this)} list={this.state.list}/>

完整代码:

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 (
      <div>
        <Link to="/index2">
          index
        </Link>
        {
          this.state.list.map((entry, index) =>
            <div key={`list-${index}`}>{entry.src}</div>
          )
        }
        <br/>
        <div>
          <ListComponent updateImg={this.updateImg.bind(this)} list={this.state.list}/>
        </div>
      </div>
    )
  }
}

2.修改子组件

import React, {Component} from 'react';

export default class List extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <button onClick={this.props.updateImg}>切换数据</button>
        {
          this.props.list.map((entry, index) =>
            <div key={`list-${index}`}>{entry.src}</div>
          )
        }
      </div>
    )
  }
}

猜你喜欢

转载自blog.csdn.net/qq_26744901/article/details/84066033