我如何从 React 中的其他组件调用组件中的函数?

How can I call a function in a component from other components in React?

我有以下组件结构:

这是输入组件。 onChange事件触发时,调用validate函数

import React, {FC, useState} from 'react';

interface InputProps {
    config : {}
}

/**
 * @param config
 * @constructor
 */
const Input: FC<InputProps> = ({config}) => {

    /**
     * @param inputValue
     */
    const validate: Function = (inputValue: any) =>
    {
        // Does input validation 
    }

    return(
        <div>
            <input 
                onChange={(event) => {
                    validate(event.target.value);
                }}
            />
        </div>
    );
}

export default Input;

这是我的App.tsx。我想调用按钮 onClick 事件中所有输入的验证。

import React, {useState} from "react";
import Form from './components/Form/Form';
import Input from './components/UI/Input/Input';
import Button from './components/UI/Button/Button';

const App = () => {

  return(
    <div className="app">
        <Form title="Simple form">
            <Input label="Email address"/>
            <Input label="Password"/>
            <Button config={{
                text: 'Sign in',
                onClick: (event) => {
                    // Here I would like to call the validatе method on the email address and  
                    // password inputs, but I don’t know how to do this yet.
                }
            }}/>
        </Form>
    </div>
  );
}

export default App;

您需要提升验证功能以在单击按钮时进行验证。 将函数的引用传递给输入等组件。

所有有用的信息都来自专家的评论部分,这里只是您需要的实现。

提升状态

我们需要将状态从 Input 组件提升到它的父组件。

App 组件中:

import React, {useState} from "react";
import Form from './components/Form/Form';
import Input from './components/UI/Input/Input';
import Button from './components/UI/Button/Button';

const App = () => {
 const [email, setEmail] = useState("");
 const [password, setPassword] = useState("");

  return(
    <div className="app">
      <Form title="Simple form">
        <Input label="Email address" value={email} onAction={setEmail} />
        <Input label="Password" value={password} onAction={setPassword} />
        <Button config={{
           text: 'Sign in',
           onClick: () => {
             validate(emailAddress);
             validate(password);
           }}
        />
      </Form>
    </div>
  );
}

export default App;

现在,在 Input 组件中:

const Input: FC<InputProps> = ({value, onAction}) => {
  return (
    <div>
      <input 
        value={value} 
        onChange={(event) => {onAction(event.target.value)}} 
      />
    </div>
  )
}

export default Input;

解释:

随着 input 元素的变化,onAction 函数将被调用。 onAction 方法是您传递给 App 组件的 setState 函数,因此 input 元素中的每个更改都会更新 emailpassword变量。

现在,在 App 组件中,您有 passwordemail 值,因此可以使用 Button 元素轻松验证它们。