我在React中有一个输入组件,通过按Enter键提交输入。我正在使用material-ui组件作为组件的基础。在onKeyDown
内部,即使是处理程序,我也通过将空字符串分配给组件状态中的唯一字段来清除状态。但是,这不起作用。我在做什么错了?
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputBase from '@material-ui/core/InputBase';
import { withStyles } from '@material-ui/core/styles';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { getAppInfo } from '../../actions/appActions.js';
const styles = theme => ({
inputRoot: {
color: 'inherit',
width: '100%',
}
})
class AppSearchBarInput extends Component {
state = {
appId: ''
}
onChange = e => {
this.setState({ appId: e.target.value });
}
onKeyDown = e => {
const { appId } = this.state;
if (e.keyCode === 13) {
this.props.getAppInfo({ appId });
this.setState({
appId: ''
});
this.props.history.push('/');
}
}
render() {
const { classes } = this.props;
return (
<InputBase
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
/>
)
}
}
const AppSearchBarWithStyles = withStyles(styles)(AppSearchBarInput);
const AppSearchBarWithStylesWithRouter = withRouter(AppSearchBarWithStyles);
export default connect(null, { getAppInfo })(AppSearchBarWithStylesWithRouter);
答案 0 :(得分:1)
您需要设置Input的值,否则它不知道要显示哪个变量,而是使用它自己的变量(不清楚)。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputBase from '@material-ui/core/InputBase';
import { withStyles } from '@material-ui/core/styles';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { getAppInfo } from '../../actions/appActions.js';
const styles = theme => ({
inputRoot: {
color: 'inherit',
width: '100%',
}
})
class AppSearchBarInput extends Component {
state = {
appId: ''
}
onChange = e => {
this.setState({ appId: e.target.value });
}
onKeyDown = e => {
const { appId } = this.state;
if (e.keyCode === 13) {
this.props.getAppInfo({ appId });
this.setState({
appId: ''
});
this.props.history.push('/');
}
}
render() {
const { classes } = this.props;
return (
<InputBase
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
value={this.state.appId}
/>
)
}
}
const AppSearchBarWithStyles = withStyles(styles)(AppSearchBarInput);
const AppSearchBarWithStylesWithRouter = withRouter(AppSearchBarWithStyles);
export default connect(null, { getAppInfo })(AppSearchBarWithStylesWithRouter);