Sra*_*ani 2 reactjs material-ui
我是 React 新手,我尝试使用 React 中的材质 UI 设计一个表单。我能够使用文本字段设计表单,但如果我使用文本字段的值属性,则无法编辑数据。当为子组件中的 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>
);
Run Code Online (Sandbox Code Playgroud)
}
在子组件中,我有这样的文本字段。由于无法发布整个代码,我发布了部分代码,这对于解决问题很有用。我也会在评论中发布粘贴 bin 链接。
<TextField
autoFocus
margin="dense"
id="emailId"
label="Email Address"
type="email"
value= {props.email}
fullWidth
/>
Run Code Online (Sandbox Code Playgroud)
请建议我该怎么做?
您可以将 Parent 的函数作为 a 发送prop给 Child 并将其设置为onChange的 prop TextField。
例如,假设您的子组件如下所示:
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"
/>
);
}
Run Code Online (Sandbox Code Playgroud)
现在您的父组件负责发送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
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是完整的演示:
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"
/>
);
}
Run Code Online (Sandbox Code Playgroud)
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
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5538 次 |
| 最近记录: |