将传递的子类方法传递给父功能组件

时间:2020-07-27 14:44:05

标签: javascript reactjs

我正在尝试从adaptValue获取Component1并在Component2中使用它。由于某些原因,这不起作用,因为我的adaptValue始终为null / undefined。是因为Parent是功能组件吗?

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;
    }
}

更新最后使父级成为类组件,并且所有工作都可以进行。想知道这是功能组件还是基于类的组件之间的兼容性问题。

1 个答案:

答案 0 :(得分:1)

setAdapt传递到Component1时... setAdapt已经是一个函数。无需将其包装在另一个包装中。 Component1将修改该值,而Component2将显示它。功能组件与行为无关。

尝试...

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 ...