父组件调用子组件的方法

本文介绍在React中,如何通过父组件设置`onRef`属性并引用子组件方法,实现父组件调用子组件的功能。具体步骤包括在子组件定义方法、父组件设置`onRef`属性、父组件定义触发子组件方法的函数,以及子组件中使用`this.props.onRef`来引用该方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接着上一篇

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

上一篇最后问到, 如果我想通过父组件中的事件来触发子组件中的方法应该怎么做呢
首先, 第一步

子组件中写一个方法

比如说例子中的获取子组件input中的值
子组件js

  getInputData = () => {
    this.nameValue = this.state.nameValue;
    this.idValue = this.state.idValue;
    // 搜索时的值要传入到父组件的接口. 
    // 所以牵扯到子组件向父组件传值
    // 1.在子组件中定义一个事件. 用父组件传递过来的属性(props),是个函数,
    // 2. 呼叫这个函数把在子组件中拿到的值传递到父组件中的函数进行处理
    this.props.getInitData(
      this.nameValue,
      this.idValue,
    )
  }
  

父组件中调用子组件的地方增加一个属性onRef

父组件js

<SearchBox
  onRef={this.onRef1} // 父组件调用子组件方法
 />

在父组件中写入这个属性的方法

父组件js

 // 父组件调用子组件的方法
  onRef1 = (ref) => {
    this.child = ref;
  }

父组件写一个方法来触发调用子组件中的方法

getChild = () => {
  this.child.getInputData(); // 如果调用了话, 那么子组件中的this.props.getInitData会被触发,
     // this.propsChildEvent这个方法也会被触发 应该会打印input中的值
  }
<Button onClick={this.getChild}>我是触发父组件调用子组件方法的方法</Button>

子组件中要引用this.props.onRef

  componentDidMount() {
    this.props.onRef(this);
  }

父组件js

class HomePage extends React.Component {
    constructor() {
        super();
        this.state = {
        }
    }

    // 一旦子组件点击就会触发此事件
    propsChildEvent = (nameValue = '', idValue = '') => {
        this.nameValue = nameValue;
        this.idValue = idValue;
        console.log('this.nameValue==',this.nameValue,
        'this.idValue==',this.idValue
    )
    }
    componentWillMount() {
        this.getData(1)
      }
     getData = (1) => {
        get('/api', {
          pageNum,
          pageSize: this.state.currentPageSize,
          exchangeNo: this.idValue || '', // 从子组件中拿到的input中的值
        })
          .then((resp) => {
              this.setState({
                tableData: resp.data.data.result,
              });
          })
          .catch((err) => {
            message.error(err.message);
          });
    }
    // 父组件调用子组件的方法
    onRef1 = (ref) => {
      this.child = ref;
    }
    getChild = () => {
      this.child.getInputData(); // 如果调用了话, 那么子组件中的this.props.getInitData会被触发,
      // this.propsChildEvent这个方法也会被触发 应该会打印input中的值
    }
    render() {
        return (
            <div>
                <SearchBox
                  onRef={this.onRef1} // 父组件调用子组件方法
                  getInitData={this.propsChildEvent}
                  getAparentAjax={() => this.getData(1)}
                />
                <Button onClick={this.getChild}>我是触发父组件调用子组件方法的方法</Button>
            </div>
        )
    }
}
export default HomePage;

子组件js

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,
    });
  }
  getInputData = () => {
    this.nameValue = this.state.nameValue;
    this.idValue = this.state.idValue;
    // 搜索时的值要传入到父组件的接口. 
    this.props.getInitData(
      this.nameValue,
      this.idValue,
    )
  }
  componentDidMount() {
    this.props.onRef(this);
  }
  // 获取所有input中的值
  onSearch = () => {
    this.nameValue = this.state.nameValue;
    this.idValue = this.state.idValue;
    // 搜索时的值要传入到父组件的接口. 
    this.props.getInitData(
      this.nameValue,
      this.idValue,
    )
    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;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值