反应材质更新TextInput值

时间:2020-11-09 12:31:56

标签: reactjs material-ui

所以我基本上是在尝试有一个输入字段来完成一个链接并将用户引向它。 但是,当我单击该按钮时,页面会正常打开,但末尾带有“ undefined”,好像输入字段未更新。 任何见识将不胜感激:)

    let workerID;
    const workerLink = "html link";
    const workerSearch = workerLink + workerID

    return (
    <div className={classes.root}>
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>
              <h1><DashboardOutlinedIcon /> Job Card</h1>
              <Moment className={classes.time}interval={1000} format="HH:mm:ss DD/MM/YYYY" />
          </Paper>
        </Grid>
        <Grid item xs={4}>
          <Paper className={classes.paper}>
              <h3><AccessibilityNewRoundedIcon /> NameGet</h3>
            <TextField id="standard-basic" label="Name:" variant="outlined" />
          </Paper>
        </Grid>
        <Grid item xs={4}>
            <Paper className={classes.paper}>
                <h3>Fetch</h3>
              <TextField id="standard-basic" label="ID:" variant="outlined" value={workerID}/>
                <a href={workerSearch} target="_blank" rel="noreferrer"><Button variant="contained" color="primary" className={classes.formstyle} value={workerID}>Search</Button></a><SearchRoundedIcon />
            </Paper>
        </Grid>
      </Grid>
    </div>
  );

1 个答案:

答案 0 :(得分:0)

您应该向输入(MaterialUI中的TextField)添加一个onChange属性,并且最好在React中使用状态而不是变量,因为如果再次更新变量,react不会相对于变量的值更新UI,但是在有状态的情况下进行更新。

import React, {useState} from 'react'

// Your Rest of code

const [workerID, setWorkerID] = useState('')//initial value of workerID is empty string

   return(
    //Rest of Code

    <TextField id="standard-basic" label="ID:" variant="outlined" value={workerID} onChange={event=>setWorkerID(event.target.value)}/>

    //Rest of Code
)