【问题标题】:How can I get the value in the parent from a child components(From Inputs)如何从子组件中获取父组件中的值(来自输入)
【发布时间】:2023-03-27 12:19:01
【问题描述】:

我正在创建一个 React 应用程序,其中我为不同的页面设置了不同的过滤器。我想在不同的子组件中潜入我的整个提交表单但是我无法在父级中链接子组件的值,我的代码如下。

父代码:

import React, { Component } from 'react';
class Dash extends Component {
    constructor(props) {
    super(props);
    this.state = {
      operator: null
    };
    this.onChange = this.onChange.bind(this);

  }
  onChange(e){
    this.setState({[e.target.name]:e.target.value});
   }
  render() {
    return (
              <div className="card-body">
                  <Operator onChange={this.operator} />
              </div>
    );
  }
}
export default Dash;

子代码:

import React, { Component } from 'react';
class Operator extends Component {
    constructor(props) {
    super(props);
    this.state = {
      operator: null
      };
      this.onChange = this.onChange.bind(this);
  }
  onChange(e){
    this.setState({[e.target.name]:e.target.value});
   }
  render() {
    const { data } = this.state;
    return (
              <div className="btn-group">
                <select className="m-wrap" id="operator-list" name="operator" onChange={this.onChange} >
                <option value="">- Choose Operator -</option>
                <option value="Digi">Digi</option>
                <option value="digi">digi</option>
                </select>
              </div>
    );
  }
}
export default Operator;

我只想将父类运算符值与子类中的选择链接。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你需要改变一些东西 onChange={this.operator}onChange={this.onChange} 在父组件中

    在孩子中

    onChange(e) {
        this.props.onChange(e)    
      }
    

    这样,您将 onchange 函数传递给子组件并从子组件调用父组件。

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 2018-08-13
      • 2019-11-22
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多