Unable to Edit the Material UI Textfields in React
我是React的新手,
我试图在React中使用材料UI设计表单。
我能够使用文本字段设计表单,但是如果我对文本字段使用value属性,则无法编辑数据。
当子组件中的Textfield调用onChange函数时,我该如何调用父函数。这是我的代码。
我在父组件中包括这样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | render() { const { name, email, mobileNumber } = this.state.serviceRequest; return ( <HomeTemplate handleShow = {this.handleShow} handleClose = {this.handleClose} name = {name} email ={email} mobileNumber = {mobileNumber} DateFnsUtils ={DateFnsUtils} handleDateChange ={this.handleDateChange} handleChange = {this.handleChange} /> ); |
} ??
在子组件中,我的文本字段是这样的。由于无法发布整个代码,我正在发布部分代码,这对于解决问题很有用。
我还将在评论中发布粘贴bin链接。
1 2 3 4 5 6 7 8 9 | <TextField autoFocus margin="dense" id="emailId" label="Email Address" type="email" value= {props.email} fullWidth /> |
请建议我该怎么做?
您可以将父级的功能作为
例如,假设您的Child组件如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | 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" /> ); } |
现在,您的父组件负责发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 /> ); } } |
这是完整的演示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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 ( <wyn>{"Parent State:" + JSON.stringify(this.state)}</wyn> <Demo onNameChange={this.handleNameChange} name={this.state.name} /> ); } } ReactDOM.render( <App />, document.getElementById('root') ); |
1 2 3 | <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"> <script src="https://unpkg.com/@material-ui/[email protected]/umd/material-ui.production.min.js"> |
您想要实现的是开发人员在使用react构建应用程序时所需要的普遍需求。
您希望子组件在调用
注意,子组件可以具有自己的状态,但是如果有多个组件需要反映相同的变化数据,则可以将状态提升到最接近的祖先。
@mehamasun已经在他的示例中说明了该操作。
Parent(state) -> Child(props) -> //Event called -> Parent(state changed via event handler) -> rerender Child(props)