【发布时间】:2018-07-25 13:49:20
【问题描述】:
几天前我开始学习 JavaScript 和 React,现在我正在尝试使用 Material Design 构建一个简单的表格,我可以通过简单的表单弹出窗口添加表格行并通过行中的图标删除行。
我想对我的“添加数据”区域中的一个字段使用 react-autosuggest,它已经以自动建议逻辑的工作方式工作。我的问题是我不知道如何获取在字段中输入的值,因此我的提交函数可以从输入值构建 JSON 并将其传递给 Symfony 控制器,该控制器构建 Doctrine Query 以将其存储在数据库中。
我有两个文件:
在 app.js 中是我的整个表体、按钮、对话框等:
render() {
const { thema, themengebiet, bemerkungen, ansprechpartner } = this.state;
return (
<MuiThemeProvider>
<div>
<AppBar position="static" color="primary">
...
</AppBar>
<Paper style={{marginTop: '10px'}}>
<Table>
<TableHead style={{ backgroundColor: 'lightgrey'}}>
<TableRow>
...
</TableRow>
</TableHead>
<TableBody>
...
</TableBody>
</Table>
</Paper>
<div style={{ marginTop: '10px', float: 'right'}}>
<Button variant="contained" color="primary" onClick={this.handleClickOpen}>Neuen Eintrag anlegen</Button>
<form id="formular" onSubmit={this.handleSubmit}>
// Here comes my Pop Up Dialog, with the autosuggest field:
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">Neues Thema vorschlagen</DialogTitle>
<DialogContent>
<DialogContentText>
Bitte alle Felder ausfüllen:
</DialogContentText>
<TextField
autoFocus
margin="dense"
label="Thema"
style={{ marginRight: '10px'}}
name="thema"
value={thema}
onChange={this.onChange}
/>
<Autosuggest
// My hope was I could just define the value of the field like a TextField:
value={ansprechpartner}
// Which does not work
/>
<TextField
...
/>
我看到您应该将 InputProps 传递给自动建议的 TextField,但似乎我不能只为这样的值传递一个变量:
在我的另一个文件 autosuggest.js 中,我返回:
return (
<Autosuggest
theme={{
container: classes.container,
suggestionsContainerOpen: classes.suggestionsContainerOpen,
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderInputComponent={renderInput}
suggestions={this.state.suggestions}
onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
renderSuggestionsContainer={renderSuggestionsContainer}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={{
classes,
placeholder: 'Search a country (start with a)',
value: {myValueHere},
onChange: this.handleChange,
'test-id': 'someid',
}}
/>
);
我想从 app.js 中的组件 autosuggest.js 访问 Autosuggest 字段的输入值,我希望将其传递给 app.js 中的状态,以便我的提交函数可以看到并存储它。
是否有一种简单的方法可以从 autosuggest.js 实例的“InputProps”中获取“值”并在我的 app.js 文件中使用它?
如果您需要其他代码或信息,请告诉我。
我这里有一个更完整的代码版本:https://codesandbox.io/s/8l6nz7p3ll(某些部分可能与我上面发布的 sn-ps 不同,这个版本当然不能工作,因为缺少数据库层/symfony 控制器)
我觉得我在这里遗漏了一些基本的 react/js 概念,请随时告诉我,请记住我对此完全陌生。
【问题讨论】:
标签: javascript reactjs material-ui