【问题标题】:Split a component into smaller components react将组件拆分成更小的组件
【发布时间】:2020-04-18 16:47:39
【问题描述】:

React 告诉我们尽可能将代码分成组件。 我有所有这些代码,我有一个表格,其中有一个按钮,可以打开一个对话框来输入数据并使用 handleChange 函数保存它们,但是将所有这些放在一起,生成数据输入非常慢。

使用handleChange函数,处理设置对象状态的钩子表单输入样式的OnChange事件。

如果我创建一个 console.log,该值会显示我输入的完整值,但在这种情况下,我在 9 上缺少最后一个字符

alias 123 456 789
State {"code":530,"email":"","alias":"123 456 78"}

我想要实现的是将表格和对话框分成两个不同的组件

如何将表格与对话框分开?

import React, { useState, useEffect } from 'react';
import MaterialTable from 'material-table';
import {TextField,Button} from '@material-ui/core';
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import  axios  from 'axios';


export default function dialog(props){ 


    const [open, setOpen] = useState(false);

    const handleClickOpen = () => {
      setOpen(true);
    };

    const handleClose = () => {
      setOpen(false);
    };

const initialState={code:0, email:'', alias:''}

const[subscription, setSubscription]=useState(initialState);

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

const handleSubmit=(event)=>{

    event.preventDefault();

    if(!subscription.code || !subscription.email || !subscription.alias) 
        return
            const postSubscription=async()=>{
                try {
                    axios.post('/api/Subscription/add',subscription);
                    props.history.push('/Subscription'); 
                }
                catch (error) {
                    console.log('error', error);
                }
            }
            postSubscription();
} 


const[user, setUser]= useState({Users:[]});

 useEffect(()=>{
    const getUser=async()=>{
            const response =await axios.get('/api/users');
            setUser(response.data);
            console.log(response.data)
    }
    getUser();
},[]);

return(
<div>
            <MaterialTable
            title="Users"
            columns={[
                  { title: 'Code', field: 'code' , type: 'numeric'},
                  { title: 'Name', field: 'name' },
                  { title: 'Lastname', field: 'lastname' },
                  { title: 'Age', field: 'age', type: 'numeric'},
            ]}
            data={user.Users}
            actions={[
                {
                  icon: 'account_box',
                  tooltip: 'Add subscription',
                  onClick:()=>{ handleClickOpen()}
                }
              ]}
          />
                  <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
                  <DialogTitle id="form-dialog-title">Subscription></DialogTitle>
                      <DialogContent>
                          <DialogContentText>
                              Subscription
                          </DialogContentText>
                              <form onSubmit={handleSubmit} >
                                  <TextField
                                      id="filled-name"
                                      name="code"
                                      label="Code"
                                      value={subscription.code}
                                      onChange={handleChange}
                                      margin="normal"
                                      variant="outlined"
                                  />
                                  <TextField
                                      id="filled-name"
                                      label="Email"
                                      value={subscription.email}
                                      name="email"
                                      onChange={handleChange}
                                      margin="normal"
                                      variant="outlined"
                                  />
                                  <TextField
                                      id="filled-multiline-static"
                                      label="Alias"
                                      value={subscription.alias}
                                      name="alias"
                                      onChange={handleChange}
                                      margin="normal"
                                      variant="outlined"
                                  />
                                  <Button
                                      variant="contained"
                                      color="primary"
                                      type="submit">
                                      Add
                                  </Button>
                              </form>
                      </DialogContent>
                  <DialogActions>
                    <Button onClick={handleClose} color="primary">
                      Cancel
                    </Button>
                  </DialogActions>
                </Dialog>
              </div>
        );
        }

【问题讨论】:

  • 您所说的“但是将所有这些放在一起会导致数据输入非常慢”是什么意思?
  • 请在What you want the Components to DO 上提供更多信息。表和 。对话框。如果我们不知道您想使用这些组件执行什么操作,我们将无法为您提供太多帮助。另外@Akshit Mehra 问题也很有效..
  • 我还建议,如果您想真正了解 React,并且时间允许,请为对话框和表格创建可重用的组件。这将为您提供有关事物如何工作的惊人见解,并允许您操纵组件的行为方式,而不是像自己一样使用它们。
  • @AkshitMehra 当我打开对话框时,在文本字段中输入数据时速度非常慢
  • @DimitrisEfst 你说得对,我已经编辑了我的问题,我认为我想要实现的目标更加清晰

标签: reactjs material-ui react-hooks


【解决方案1】:

好吧,尽管我发表了评论,但我会尝试解释我将如何评估这种情况。

这只是我自己的想法,来源于我自己的经验。这并不意味着,它是唯一或最好的方法。

我会从内到外。我会创建一个可重用的组件:

  1. 对话框

所以,到目前为止一切顺利。就像你想的那样。最重要的是,我会将所有 SubmitHandlers 和相关代码移至该组件(对话框)。比如:

// This functions and all its dependancies, have nothing to do with the Table.
- handleClose
- handleChange
- open 

我还会将一个数组传递给 &lt;TextField /&gt; 组件,以最大限度地减少渲染中的代码,并像这样使用 ES6 map

 <Fragment>
   {TextFields.map(
     (field: ITextField):ReactNode => (
       <Fragment key={field.name}>{this.renderTextField(field)}</Fragment>
     ))}
 </Fragment>

使用上面的render(),将更具可读性,并且您将来可以更轻松地扩展表单。 You just add more elements to the Array.

作为最后一步,我将在父组件内调用对话框和表格组件。以防万一我需要操作来自这两个组件的各种来源(Redux - LocalComponentState)的数据。示例:

export default class ParentComponent extends Component {
 // State
 // Props

 render() {
   <TableComponent propsForTableComponent={propsForTableComponent} />
   <DialogComponent propsForDialogComponent={propsForDialogComponent} />
 }
}

再次,不确定您所说的慢是什么意思。但如果我能提供更多帮助,请询问。希望我能帮上忙。

【讨论】:

  • 谢谢你让我知道如何分离组件
猜你喜欢
  • 2011-04-26
  • 2021-11-18
  • 2011-02-21
  • 2017-12-11
  • 1970-01-01
  • 2022-07-07
  • 2022-12-02
  • 1970-01-01
  • 2011-10-26
相关资源
最近更新 更多