如何构建带有钩子的多功能组件表单?

时间:2019-09-24 00:58:40

标签: javascript forms components react-hooks

我有一个App.js表单(父),该表单呈现了两个单独的(子)组件来构建此表单:Email.js和Button.js。

单击按钮时,警报应显示收集的输入。

据我所知,下面的代码。有人可以帮我吗?

  1. 完成两个部分,然后
  2. 是否将它们成功连接到Parent(App.js)?

作为练习,我了解了它如何与类组件一起工作。我很难将其转换为具有多个子代的功能组件。

这是我的App.js结构:

import React, { useState } from 'react';
import Button from './components/Button.js';
import Email from './components/Email.js';


function App() {

  return (
    <div>
      <form>
        <Email />
        <Button />
      </form>
    </div> 
  );
}

export default App;

我的Email.js:

import React, { useState } from "react"

function Email() {

  const [input, inputChange] = useState({email: ""})

  const handleChange = (event) => {
    inputChange({[event.target.name]: event.target.value})
  } 

  return (
    <div className = "form-group">
        <label>Email adress </label>
        <input
            type="text"
            name="email"
            placeholder="Enter your email!"
            value = {input.email}
            onChange = {handleChange}
        />
    </div>
  )
}

export default Email

和我的按钮:

import React, { useState} from "react"

function Button() {

    return (
        <div>
            <button onClick={handleClick}>Click me></button>
        </div>
    )

}

export default Button 

1 个答案:

答案 0 :(得分:0)

看看这是否对您有用:

function App() {

  const [email,setEmail] = React.useState('hello@world.com');
  
  function changeEmail(event) {
    setEmail(event.target.value);
  }
  
  function handleClick() {
    alert('The email entered was: ' + email);
  }

  return(
    <React.Fragment>
      <Email
        email={email}
        changeEmail={changeEmail}
      />
      <Button
        handleClick={handleClick}
      />
    </React.Fragment>
  );
}

function Email(props) {
  return(
    <input type='email' value={props.email} onChange={props.changeEmail}/>
  );
}

function Button(props) {
  return(
    <button onClick={props.handleClick}>Click</button>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>