我对 react 还很陌生,我必须创建这个图标菜单。我的问题是我的handleChange 现在不起作用。我有图标菜单,我可以看到可能的值菜单,但我无法选择其中任何一个。有人可以解释一下使这段代码工作的最佳方法吗?我正在使用图标菜单组件“https://v0.material-ui.com/#/components/icon-menu”。谢谢
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
class MatchPintOwnerFilter extends Component {
constructor() {
super();
this.state = {
values: [],
};
}
handleChange(event, index, values) {
this.setState({ values });
}
render() {
const { possibleValues, title } = this.props;
return (
<SelectField
autoWidth
floatingLabelText={title}
multiple={false}
value={possibleValues}
onChange={this.handleChange.bind(this)}
>
{Object.keys(possibleValues).map(possibleValue => (
<MenuItem
key={possibleValue}
value={possibleValue}
primaryText={possibleValues[possibleValue]}
/>
))}
</SelectField>
);
}
}
MatchPintOwnerFilter.propTypes = {
title: PropTypes.string,
possibleValues: PropTypes.shape(),
newValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
MatchPintOwnerFilter.defaultProps = {
title: 'Frequency',
possibleValues: {
0: 'status 0',
1: 'status 1',
2: 'status 2',
3: 'status 3',
4: 'status 4',
5: 'status 5',
},
newValue: '1',
};
export default MatchPintOwnerFilter;
最佳答案
您没有正确设置 SelectField value 属性:
const { possibleValues } = this.props;
< SelectField
autoWidth
floatingLabelText = {
title
}
multiple = {
false
}
value = {
possibleValues
}
onChange = {
this.handleChange.bind(this)
} >
您想要做的是通过传递一个名为 possibleValues 的 Prop 来控制 SelectionField,该 Prop 永远不会改变。如果您想创建一个受控组件,您应该提升State Up,然后将其作为 prop 再次传递给您的组件。
handleChange(event, index, value) {
this.props.onSelectionFieldChange(value);
}
在你的父组件中你应该有类似的内容:
_onSelectionFieldChange(possibleValues) {
this.setState({ possibleValues });
}
<MatchPintOwnerFilter onSelectionFieldChange={this._onSelectionFieldChange.bind(this)} possibleValues={this.state.possibleValues}>
希望有帮助。
关于javascript - 处理 React 中的状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52363717/