Вызов функции с именем functionA из компонента класса ClassComponentA в файле fileA в компоненте функции B в файле functionComponentA в REACT 17

#javascript #reactjs #function #methods #components

#javascript #reactjs #функция #методы #Компоненты

Вопрос:

У меня есть два компонента, один из которых является компонентом класса, а другой — функциональным компонентом. Я хочу вызвать метод в functionComponentA, помещенный в classComponentA. Я сделал это, отправив метод в props. Я не хочу делать это таким образом

 import React, { Component } from 'react'
import functionComponentA from './functionComponentA'
class ClassComponentA extends Component {
    constructor(props) {
        super(props)
        this.state = {
            coolVariable : 1
    }

    functionA= () => {
        return "something"
}
    render(){

    const functionComponentA = <functionComponentA method= {this.doStuff.bind()}/>
    return functionComponentA
    }
}
export default ClassComponentA

//the code below is in a different file
import ClassComponentA from './ClassComponentA'
function FunctionComponentA (props){
    return <input onBlur= {event => {ClassComponentA.functionA()}/>
}
export default FunctionComponentA
 

когда я делаю, как в приведенном выше коде, я получаю ClassComponentA__WEBPACK_IMPORTED_MODULE_2__.default.functionA не является функцией
Я не хочу отправлять функцию в качестве реквизита, но я хочу вызвать ее из файла, в котором размещен другой компонент. Можно ли это сделать каким-либо образом и что я делаю не так?

 import React, { Component } from 'react'
import functionComponentA from './functionComponentA'
class ClassComponentA extends Component {
    constructor(props) {
        super(props)
        this.state = {
            coolVariable : 1
    }

    functionA= () => {
        return "something"
}
    render(){

    const functionComponentA = <functionComponentA method= {this.doStuff.bind()}/>
    return functionComponentA
    }
}
export default ClassComponentA

//code below is from a different file
function FunctionComponentA (props){
    return <input onBlur= {event => {props.functionA()}/>
}
export default FunctionComponentA
 

Комментарии:

1. Я думаю functionComponentA , следует начинать с заглавной буквы. functionA доступен только после «создания экземпляра»

Ответ №1:

У вас много опечаток и несколько основных ошибок:

 // typo: functionComponentA, no need to bind if you use arrow function
// there is no function doStuff, rename from functionA
<FunctionComponentA method={this.doStuff}/>

// call method() as the prop name and not functionA().
function FunctionComponentA (props){
    return <input onBlur={()=> props.method()} />
}
 

Наконец, код должен выглядеть так:

 class ClassComponentA extends Component {
  doStuff = () => {
    console.log("hello");
  };
  render() {
    return <FunctionComponentA method={this.doStuff} />;
  }
}

function FunctionComponentA(props) {
  return <input onBlur={props.method} />;
}