简体   繁体   中英

React pass child class method to parent functional component

I am trying to get adaptValue from Component1 and use it in Component2 . For some reason this does not work since my adaptValue is always null/undefined. Is it because Parent is a functional component?

const Parent = (props) => {
    const [adaptValue, setAdapt] = useState(null);
    return (
        <div>
            <Component1 setAdapt={setAdapt}/>
            <Component2 adaptValue={adaptValue}/>
        </div>
    )
}

export default class Component1 extends Component {
    constructor(props) {
      super(props);
    }
  
    adaptValue = (value) =>{
        DO_SOMETHING_WITH_VALUE
    }

    componentDidMount() {
        this.props.setAdapt(this.adaptValue);
    }

    render() {
        return something;
    }
}

export default class Component2 extends Component {
    constructor(props) {
      super(props);
    }
  
    someFunction = (value) =>{
        ...
        //adaptValue is always undefined
        this.props.adaptValue(value)
        ...
    }

    render() {
        return something;
    }
}

UPDATE Made the parent a class component in the end and all works. Wondering whether this is a compatibility issue between functional or class-based components.

When passing setAdapt to Component1 ... setAdapt is already a function. There is no need to wrap it in another one. Component1 will modify the value, and Component2 will display it. Function Components have nothing to do with the behavior.

Try...

App.js

import React, { useState } from "react";
import "./styles.css";
import Component1 from "./Component1";
import Component2 from "./Component2";

export default function App() {
  const [adaptValue, setAdapt] = useState(null);

  return (
    <div>
      <Component1 setAdapt={setAdapt} />
      <Component2 adaptValue={adaptValue} />
    </div>
  );
}

Component1.js

import React, { Component } from "react";

export default class Component1 extends Component {
  handleClick = () => {
    this.props.setAdapt("New Value");
  };

  render() {
    return <button onClick={() => this.handleClick()}>Set Value</button>;
  }
}

Component2.js

import React, { Component } from "react";

export default class Component2 extends Component {
  render() {
    return !!this.props.adaptValue ? (
      <h1>{`"${this.props.adaptValue}" <- Value of adaptValue`}</h1>
    ) : (
      <h1>adaptValue Not Assigned</h1>
    );
  }
}

Sandbox Example...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM