【问题标题】:How to send the Input Fields in React Function component to a function如何将 React 函数组件中的输入字段发送到函数
【发布时间】:2021-06-18 12:59:17
【问题描述】:

我的反应功能组件中有 4 个输入字段, 我做了一个函数contactMeButtonPressed,我想抓取所有的输入 当我点击联系我按钮时,姓名、电子邮件、公司名称、消息。

我是否需要在这里设置一个状态,或者我可以通过我的代码实现我的目标?

  • 现在我正在控制台上打印以进行测试,稍后我会将信息发送到我的 Django 后端。

contact.js

import React, {Component} from 'react';
import Navbar from "./Navbar";
import {useStyles} from '../../static/styles/styles';
import {TextField, Typography, Button, Grid, Box, withStyles} from "@material-ui/core";
import SendIcon from "@material-ui/icons/Send";
import {WithStyles, makeStyles} from "@material-ui/core/styles";

    const InputField = withStyles({
        root: {
            "& label.Mui-focused": {
                color: "tomato",
            },
            "& label": {
                color: "tan",
            },
            "& .MuiOutlinedInput-root": {
                "& fieldset": {
                    borderColor: "tan",
                },
                "&:hover fieldset": {
                    borderColor: "tan"
                },
                "&.Mui-focused fieldset": {
                    borderColor: "tan",
                }
            }
        },
    })(TextField);
    
    function contactMeButtonPressed() {
        const requestOptions = {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({
    
                // how to get all the InputField from box component in Contact
            }),
        };
        fetch("/backend/contact-me/", requestOptions)
            .then((response) => response.json())
            .then((data) => console.log(requestOptions));
    }
    
    const Contact = () => {
        const classes = useStyles(); // To use the CSS Styles in styles.js
        return (
            <>
                <Box component="div" style={{background: "#233", height: "100vh"}}>
                    <Navbar/>
                    <Grid container justify="center">
                        <Box component="form" className={classes.form}>
                            <Typography variant="h5" style={{
                                color: "tomato",
                                textAlign: "center",
                                textTransform: "uppercase",
                            }}
                            >
                                Contact me
                            </Typography>
                            <InputField
                                fullWidth={true}
                                label="Name"
                                variant="outlined"
                                inputProps={{style: {color: "white"}}}
                                margin="dense"
                                size="medium"
                            />
                            <br/>
                            <InputField
                                fullWidth={true}
                                label="Email"
                                variant="outlined"
                                inputProps={{style: {color: "white"}}}
                                margin="dense"
                                size="medium"
                            />
                            <br/>
                            <InputField
                                fullWidth={true}
                                label="Company Name"
                                variant="outlined"
                                inputProps={{style: {color: "white"}}}
                                margin="dense"
                                size="medium"
                            />
                            <br/>
                            <InputField
                                fullWidth={true}
                                label="Message"
                                variant="outlined"
                                inputProps={{style: {color: "white"}}}
                                margin="dense"
                                size="medium"
                            />
                            <br/>
                            <Button
                                className={classes.contactButton}
                                variant="outlined"
                                fullWidth={true}
                                endIcon={<SendIcon/>}
                                onClick={contactMeButtonPressed}
                            >
                                Contact me
                            </Button>
                        </Box>
                    </Grid>
                </Box>
            </>
        );
    };
    
    export default Contact;

使用 Hooks 的解决方案代码:

import React, {Component} from 'react';
import Navbar from "./Navbar";
import {useStyles} from '../../static/styles/styles';
import {TextField, Typography, Button, Grid, Box, withStyles} from "@material-ui/core";
import SendIcon from "@material-ui/icons/Send";
import {WithStyles, makeStyles} from "@material-ui/core/styles";
import {useState} from 'react';


const InputField = withStyles({
    root: {
        "& label.Mui-focused": {
            color: "tomato",
        },
        "& label": {
            color: "tan",
        },
        "& .MuiOutlinedInput-root": {
            "& fieldset": {
                borderColor: "tan",
            },
            "&:hover fieldset": {
                borderColor: "tan"
            },
            "&.Mui-focused fieldset": {
                borderColor: "tan",
            }
        }
    },
})(TextField);


const Contact = () => {
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [company_name, setCompany_name] = useState('')
    const [message, setMessage] = useState('')

    function contactMeButtonPressed() {
        const requestOptions = {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({
                name: name,
                company_name: company_name,
                message: message,
                email: email,
            }),
        };
        fetch("/backend/contact-me/", requestOptions)
            .then((response) => response.json())
            .then((data) => console.log(requestOptions));
    }

    const classes = useStyles(); // To use the CSS Styles in styles.js
    return (
        <>
            <Box component="div" style={{background: "#233", height: "100vh"}}>
                <Navbar/>
                <Grid container justify="center">
                    <Box component="form" className={classes.form}>
                        <Typography variant="h5" style={{
                            color: "tomato",
                            textAlign: "center",
                            textTransform: "uppercase",
                        }}
                        >
                            Contact me
                        </Typography>
                        <InputField
                            value={name}
                            onChange={e => setName(e.target.value)}
                            fullWidth={true}
                            label="Name"
                            variant="outlined"
                            inputProps={{style: {color: "white"}}}
                            margin="dense"
                            size="medium"
                        />
                        <br/>
                        <InputField
                            value={email}
                            onChange={e => setEmail(e.target.value)}
                            fullWidth={true}
                            label="Email"
                            variant="outlined"
                            inputProps={{style: {color: "white"}}}
                            margin="dense"
                            size="medium"
                        />
                        <br/>
                        <InputField
                            value={company_name}
                            onChange={e => setCompany_name(e.target.value)}
                            fullWidth={true}
                            label="Company Name"
                            variant="outlined"
                            inputProps={{style: {color: "white"}}}
                            margin="dense"
                            size="medium"
                        />
                        <br/>
                        <InputField
                            value={message}
                            onChange={e => setMessage(e.target.value)}
                            fullWidth={true}
                            label="Message"
                            variant="outlined"
                            inputProps={{style: {color: "white"}}}
                            margin="dense"
                            size="medium"
                        />
                        <br/>
                        <Button
                            className={classes.contactButton}
                            variant="outlined"
                            fullWidth={true}
                            endIcon={<SendIcon/>}
                            onClick={contactMeButtonPressed}
                        >
                            Contact me
                        </Button>
                    </Box>
                </Grid>
            </Box>
        </>
    );
};

export default Contact;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    是的,您需要状态来管理 reactjs 中的数据。由于您使用的是功能组件,因此管理数据非常容易。您可以使用useState 来管理数据。我将向您展示一个管理数据以响应输入的示例。

    使用以下命令导入使用状态

    import React, {useState} from 'react';
    

    以下命令用于声明状态变量。

    const [text, setText] = useState('')
    

    以下命令是输入声明。

    <input
      value={text}
      onChange={e => setText(e.target.value)}
      required
    ></input>
    

    最后,您的数据将以文本状态存储,您可以使用该文本状态将数据发送到后端。

    【讨论】:

    • 这是否意味着每个输入都需要 usestate 函数?以及如何将所有值发送到我的contactMeButtonPressed 函数,以便我可以将它们发送到我的后端?我还没有学习钩子,但我现在正在阅读它们
    • @Alwayslearning 在您的代码中添加上述 sn-ps 和钩子后,现在输入选项卡设置为存储状态中的值。在输入字段中键入任何值后,例如,如果您在此处键入“abc”,则“abc”存储在text 中,您可以在组件中使用该值,也可以将其传递给另一个组件。它几乎就像组件的全局变量一样。
    • 它似乎工作,我已经添加了更新代码,如果你看看我是否正确使用它们将不胜感激
    【解决方案2】:

    在 Material 中,您的 InputField 组件可以有一个 id 标签,所以我要做的是在 InputField 组件上设置一个 id,然后当您单击您的 contactMeButtonPressed 时,您可以获得所有字段,如下所示:

    function contactMeButtonPressed() {
            const Name = document.getElementByID('name').value;
            const Email = document.getElementByID('email').value;
            const Company Name = document.getElementByID('company-name').value;
            const Message = document.getElementByID('message').value;
    
            const requestOptions = {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify({
        
                    // how to get all the InputField from box component in Contact
                }),
            };
            fetch("/backend/contact-me/", requestOptions)
                .then((response) => response.json())
                .then((data) => console.log(requestOptions));
        }
    
    

    然后将这些值格式化为您的数据库所期望的。

    【讨论】:

    • 感谢您的宝贵时间!我最后使用了 Hooks,它现在似乎可以工作,添加了更新的代码
    • 就我个人而言,我认为您不需要在组件中使用任何状态才能使其工作,因为您可以使用 id 从输入字段中获取信息,但我很高兴能提供帮助.
    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多