搜索组件 - 父组件向子组件传值(子组件调用父组件方法)

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

接着上一篇文章继续 , 传送门, 上一篇地址

搜索组件 - react中子组件向父组件中传值

接着, 在上一篇中, 在父组件中拿到了子组件input框中的内容值, 然后在父组件中使用, 接下来点击搜索以后,我肯定是需要再次调用接口来重新渲染搜索的页面的

所以 在父组件调用子组件的位置上添加一个属性, 向子组件传递

<SearchBox
   getInitData={this.propsChildEvent}
    getAparentAjax={() => this.getData(1)}
 />

子组件中只需要使用this.props.getAparentAjax();就可以调用此方法

整个的代码
父组件index.js

import React from 'react';
import TopHead from '../topToopbar/topHead.js'
import { Table, message } from 'antd';
import SearchBox from './searchBox.js';
import { get } from '../../util/http'
import { Link } from 'react-router-dom';
import moment from 'moment';
import $ from 'jquery';

class HomePage extends React.Component {
    constructor() {
        super();
        this.state = {
          nameValue: '',
          idValue: '',
          tableColumns: [],
          tableData: [],
          currentPageSize: 10,
        }
        this.tableColumns = [];
    }
    componentDidMount() {
        // var that = this;
        // $.ajax({
        //     type: 'get',
        //     url: 'http://10.70.119.183:8084//api?pageNum=1&pageSize=10&exchangeNo=',
        //     dataType: 'json',
        //     async: true,
        //     success: function(data) {
        //         that.setState({ arr: data.data });
        //         console.log(that.state.arr)
        //     }
        // })
        
    }
    // 一旦子组件点击就会触发此事件
    propsChildEvent = (nameValue = '', idValue = '') => {
        this.nameValue = nameValue;
        this.idValue = idValue;
        console.log('this.nameValue==',this.nameValue,
        'this.idValue==',this.idValue
    )
    }
    componentWillMount() {
        this.tableColumns.push({
          title: '单号',
          dataIndex: 'exchangeNo',
          key: 'exchangeNo',
        },
        {
            title: '获取时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text, record) => moment(record.createTime).format('YYYY-MM-DD'),
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => {
              const data = JSON.stringify({ exchangeNo: record.exchangeNo });
              return (
                <span>
                  <Link to={`/platform/cascadeManage/exchangeUseDetail/${data}`}>使用详情</Link>
                </span>
              );
           },
        }
        );
        this.getData(1)
      }
     getData = (pageNum) => {
        get('/api', {
          pageNum,
          pageSize: this.state.currentPageSize,
          exchangeNo: this.idValue || '', // 从子组件中拿到的input中的值
        })
          .then((resp) => {
              this.setState({
                tableData: resp.data.data.result,
                resPages: resp.data.data,
                loading: true,
                currentPage: pageNum,
              });
          })
          .catch((err) => {
            message.error(err.message);
          });
    }
    render() {
        return (
            <div>
                <SearchBox
                  getInitData={this.propsChildEvent}
                  getAparentAjax={() => this.getData(1)}
                />
                <Table pagination columns={this.tableColumns} dataSource={this.state.tableData} />
            </div>
        )
    }
}
export default HomePage;

子组件searchBox.js

import React from 'react';
import { Link } from 'react-router-dom';
import { Input, message, Button, Row, Col } from 'antd';

class SearchBox extends React.Component {
  constructor() {
    super();
    this.state = {
      nameValue: '',
      idValue: '',
    }
  }
  changeFieldValue = (e, key) => {
    const value = typeof e === 'object' ? e.target.value : e;
    this.setState({
      [key]: value,
    });
  }
  // 获取所有input中的值
  onSearch = () => {
    this.nameValue = this.state.nameValue;
    this.idValue = this.state.idValue;
    // 搜索时的值要传入到父组件的接口. 
    // 所以牵扯到子组件向父组件传值
    // 1.在子组件中定义一个事件. 用父组件传递过来的属性(props),是个函数,
    // 2. 呼叫这个函数把在子组件中拿到的值传递到父组件中的函数进行处理
    this.props.getInitData(
      this.nameValue,
      this.idValue,
    )
    // 3. 去父组件中引用子组件的地方定义一个函数来接收this.props.getInitData传递过来的值
    // 4.点击搜索以后, 还需要请求接口, 那么就需要子组件调用父组件方法, 或者说父组件向子组件传递方法,
    // 这个和父组件向子组件传值是相同的 都是用到了props
    this.props.getAparentAjax();
  }
    render() {
        return (
          <div>
            <Row gutter={16}>
              <Col span={3}><span>名称:</span></Col>
              <Col span={6}>
              <Input
                placeholder="请输入"
                onChange={ (e) => { this.changeFieldValue(e, 'nameValue'); } }
                value={this.state.nameValue}
              /></Col>
            </Row>
            <Row gutter={16}>
              <Col span={3}><span>id:</span></Col>
              <Col span={6}>
              <Input
                placeholder="请输入"
                onChange={ (e) => { this.changeFieldValue(e, 'idValue'); } }
                value={this.state.idValue}
                width="320px"
              /></Col>
            </Row>
            <Row gutter={16}>
              <Col offset={3} span={4}>
              <Button
                type="primary"
                style={{ marginLeft: '10px' }}
                className="searchButton"
                onClick={this.onSearch}
                width="320px"
              >
                搜索
              </Button></Col>
            </Row>
          
          </div>
        )
    }
}
export default SearchBox;

点击搜索重新调用
image.png

上面是我点击搜索的时候通过触发onSearch事件, 才能调用this.props.getInitData 把它传递给父组件,我才能在父组件中拿到该值.

现在我不想通过点击搜索来拿到input中的值, 子组件中只有一个搜索事件可以触发使我拿到this.props.getInitData , 现在我在子组件中另外写一个方法来触发获取this.props.getInitData , 那么我就需要在父组件中调用子组件的方法
接下来讲解一下

父组件调用子组件的方法

猜你喜欢

转载自blog.csdn.net/zm_miner/article/details/84583156