如何在React的子类组件中调用父方法

时间:2020-10-17 09:37:42

标签: reactjs react-native

    //child component
    import React, { Component } from 'react'
    const NavButton = ({ active, title, href, onSetActive }) => {
        return (
            <button
                className={active ? "btn btn-light regular-btn active" : "btn btn-light regular-btn"}
                href={href}
                onClick={onSetActive} >
                {title}
            </button>
        )
    }
    class Child extends Component {
        constructor(props) {
            super(props);
            this.state = {
                activeIndex: 1,
                buttons: [
                    {
                        title: "1",
                        key: 0,
                        value: 1
                    },
                    {
                        title: "3",
                        key: 1,
                        value: 3
                    }
                ]
            }
        }
       //It was changing active index
        handleChangeActive(newActiveIndex) {
            // console.log("Working");
            this.setState({ activeIndex: newActiveIndex });
        }
    
        render() {
            const { activeIndex } = this.state;
            return (
                <div>
                    <nav id="navbarMain">
                        <div className="navbar-nav flex-row">
                            {this.state.buttons.map((button, buttonIndex) =>
                                /* determine which nav button is active depending on the activeIndex state */
                                <NavButton onClick={() => this.investmentHandler.bind(this)} value={button.value} onSetActive={() => this.handleChangeActive(buttonIndex)} active={buttonIndex === activeIndex} title={button.title} key={button.key} />)}
    
                        </div>
                    </nav>
                </div>
            )
        }
    }
    
    export default Child
    
    
    // parent component
    import React, { Component } from 'react'
    import Child from './Child';
    class Parent extends Component {
        constructor(props) {
            super(props)
    
       

 this.state = {
            firstValue: 1,
            secondValue: 3,
            result: ''
        }
        
        // this.add = this.add.bind(this);
    }
//calculating the input values
    Add = () => {
        var { firstValue, secondValue, result } = this.state;

        result = firstValue + secondValue;
        console.log(result);
        document.getElementById("result").innerHTML = result;
    }
    render() {
        return (
            <>
//Child component is used inside the parent component using props

                <Child investmentHandler={this.add} />
                <p id="result">Result</p>
            </>
    
            )
        }
    }
    export default Parent

我需要事件处理程序(添加)必须在子组件内部工作。 如何在类组件中使用道具使用事件处理程序。 在React中如何在子类组件中调用父方法。 我尝试过使用道具,但无法正常工作。 基于子组件输入按钮,它必须获取结果。

2 个答案:

答案 0 :(得分:0)

检查这可能有帮助

 //child component
    import React, { Component } from 'react'
    const NavButton = ({ active, title, href, onSetActive }) => {
        return (
            <button
                className={active ? "btn btn-light regular-btn active" : "btn btn-light regular-btn"}
                href={href}
                onClick={onSetActive} >
                {title}
            </button>
        )
    }
    class Child extends Component {
        constructor(props) {
            super(props);
            this.state = {
                activeIndex: 1,
                buttons: [
                    {
                        title: "1",
                        key: 0,
                        value: 1
                    },
                    {
                        title: "3",
                        key: 1,
                        value: 3
                    }
                ]
            }
        }
       //It was changing active index
        handleChangeActive(newActiveIndex) {
            // console.log("Working");
            this.setState({ activeIndex: newActiveIndex });
        }
    
        render() {
            const { activeIndex } = this.state;
            return (
                <div>
                    <nav id="navbarMain">
                        <div className="navbar-nav flex-row">
                            {this.state.buttons.map((button, buttonIndex) =>
                                /* determine which nav button is active depending on the activeIndex state */
                                <NavButton onClick={() => this.props.investmentHandler()} value={button.value} onSetActive={() => this.handleChangeActive(buttonIndex)} active={buttonIndex === activeIndex} title={button.title} key={button.key} />)}
    
                        </div>
                    </nav>
                </div>
            )
        }
    }
    
    export default Child
    
    
    // parent component
    import React, { Component } from 'react'
    import Child from './Child';
    class Parent extends Component {
        constructor(props) {
            super(props)
    
       

 this.state = {
            firstValue: 1,
            secondValue: 3,
            result: ''
        }
        
        // this.add = this.add.bind(this);
    }
//calculating the input values
    Add = () => {
        var { firstValue, secondValue, result } = this.state;

        result = firstValue + secondValue;
        console.log(result);
        document.getElementById("result").innerHTML = result;
    }
    render() {
        return (
            <>
//Child component is used inside the parent component using props

                <Child investmentHandler={this.Add} />
                <p id="result">Result</p>
            </>
    
            )
        }
    }
    export default Parent

答案 1 :(得分:0)

在Child类上,您的组件NavButton具有一个onClick属性,该属性调用onSetActive,因此您可以在onSetActive函数上调用investmentHandler:

//child component
import React, { Component } from "react";
const NavButton = ({ active, title, href, onSetActive }) => {
  return (
    <button
      className={
        active
          ? "btn btn-light regular-btn active"
          : "btn btn-light regular-btn"
      }
      href={href}
      onClick={onSetActive}
    >
      {title}
    </button>
  );
};
class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeIndex: 1,
      buttons: [
        {
          title: "1",
          key: 0,
          value: 1,
        },
        {
          title: "3",
          key: 1,
          value: 3,
        },
      ],
    };
  }
  //It was changing active index
  handleChangeActive(newActiveIndex) {
    // console.log("Working");
    this.setState({ activeIndex: newActiveIndex });
    this.props.investmentHandler();
  }

  render() {
    const { activeIndex } = this.state;
    return (
      <div>
        <nav id="navbarMain">
          <div className="navbar-nav flex-row">
            {this.state.buttons.map((button, buttonIndex) => (
              /* determine which nav button is active depending on the activeIndex state */
              <NavButton
                value={button.value}
                onSetActive={() => this.handleChangeActive(buttonIndex)}
                active={buttonIndex === activeIndex}
                title={button.title}
                key={button.key}
              />
            ))}
          </div>
        </nav>
      </div>
    );
  }
}

export default Child;

在Parent类上,当从Child类获取道具时,您应该在应调用“ this.Add”时调用“ this.add”:

// parent component
import React, { Component } from 'react'
import Child from './Child';
class Parent extends Component {
    constructor(props) {
        super(props)

this.state = {
        firstValue: 1,
        secondValue: 3,
        result: ''
    }
    
    // this.add = this.add.bind(this);
}
//calculating the input values
Add = () => {
    console.log('Im here')
    var { firstValue, secondValue, result } = this.state;

    result = firstValue + secondValue;
    console.log(result);
    document.getElementById("result").innerHTML = result;
}
render() {
    return (
        <>
            <Child investmentHandler={this.Add} />
            <p id="result">Result</p>
        </>

        )
    }
}
export default Parent

我做了几处更改,并且代码对我有用。