首页 > 解决方案 > 无法在 React 中编辑 Material UI 文本字段

问题描述

我是 React 新手,我尝试在 React 中使用 Material UI 设计一个表单。我能够使用文本字段设计表单,但如果我对文本字段使用 value 属性,则无法编辑数据。当子组件中的 Textfield 调用 onChange 函数时,我如何调用父函数。这是我的代码。

在父组件中,我包括这样

 render() {
const { name, email, mobileNumber } = this.state.serviceRequest;

return (
  <div>
  <HomeTemplate 
  handleShow = {this.handleShow}
  handleClose = {this.handleClose}
  name = {name}
  email ={email}
  mobileNumber = {mobileNumber}
  DateFnsUtils ={DateFnsUtils}
  handleDateChange ={this.handleDateChange}
  handleChange = {this.handleChange}
   /> 
 </div>
  );

}

在子组件中,我有这样的文本字段。由于无法发布整个代码,我发布了对解决问题有用的部分代码。我也会在评论中发布粘贴箱链接。

 <TextField
            autoFocus
            margin="dense"
            id="emailId"
            label="Email Address"
            type="email"
            value= {props.email}
            fullWidth
          />

请建议我该怎么做?

标签: reactjsmaterial-ui

解决方案


您可以将 Parent 的函数作为 aprop发送给 Child 并将其设置为onChangeprop of TextField

例如,假设您的 Child 组件如下所示:

function Demo(props) {
  return (
    <TextField
      fullWidth
      id="standard-name"
      label="Name"
      value={props.name}              // it gets value from prop
      onChange={props.onNameChange}   // it gets handler function from prop too!
      margin="normal"
    />
  );
}

现在您的父组件负责发送props.nameprops.onNameChange

class App extends React.Component {
  state = {
    name: "Sleepy cat"
  };

  handleNameChange = event => {
    this.setState({ name: event.target.value });
  };

  render() {
    return (
        <Demo 
          onNameChange={this.handleNameChange}  // send a function as prop, that will change the state in parent
          name={this.state.name}                // send the state of parent to child
        />
    );
  }
}

这是完整的演示:

const {TextField} = window['material-ui'];

function Demo(props) {
  return (
    <TextField
      fullWidth
      id="standard-name"
      label="Name"
      value={props.name}
      onChange={props.onNameChange}
      margin="normal"
    />
  );
}

class App extends React.Component {
  state = {
    name: "Sleepy cat"
  };

  handleNameChange = event => {
    this.setState({ name: event.target.value });
  };

  render() {
    return (
      <div>
        <code>{"Parent State: " + JSON.stringify(this.state)}</code>
        <Demo onNameChange={this.handleNameChange} name={this.state.name} />
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@3.9.2/umd/material-ui.production.min.js"></script>

<div id="root"></div>


推荐阅读