reactjs - 无法在 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
/>
请建议我该怎么做?
解决方案
您可以将 Parent 的函数作为 aprop
发送给 Child 并将其设置为onChange
prop 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.name
和props.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>
推荐阅读
- ios - 使用领域保持登录状态
- angular - 如何使用 rxjs 定时器实现一个 http poller
- graphql - GraphIql apollo 引擎不支持的内容类型
- vaadin - 用于字符串数组的 vaadin-grid-filter 不起作用
- mysql - mysql函数变量集不起作用
- php - 可以用多个键做 JSON_EXTRACT 吗?
- mysql - Sequelize 限制和订单不适用于条件查询
- javascript - 如何从 Google Maps API 中的拖动事件中获取自动完成地址?
- arrays - 为什么这个拆分字符串表达式不给我一个数组?
- java - 如何从嵌套的 JSON 中检索值