我使用受控文本字段,以便监听该字段中值的变化,并在以大写或小写形式请求条目的情况下强制该值。
所以我必须使用组件状态的 value 属性。
不幸的是,如果我在另一个 Redux 组件中使用这个组件,并且想通过连接到 Redux 的全局状态的属性来更新这个字段,我不知道该怎么做。
如果我使用我的组件的属性来对我的受控字段进行赋值,那么在字段的 onChange 之后,我会丢失与条目相关的修改(因为我没有按值对状态进行赋值)。
如果我在受控字段的估值中使用状态,则根本不会检索 Redux 道具提供的值。有任何想法吗?
我的组件的简化代码片段:
import { TextField } from '@material-ui/core';
import React from 'react';
import {
MyInputProperties,
defaultInputFieldPropsValue
} from './MyInputProperties';
import { MyInputState } from './MyInputState';
export class MyInput
extends React.Component<MyInputProperties, MyInputState> {
static readonly VERSION: number = 100;
public static defaultProps = defaultInputFieldPropsValue;
constructor(props: MyInputProperties) {
super(props);
this.state = {
...this.state,
value: this.props.value
};
}
protected render(): JSX.Element {
const {
error,
focused,
helperText,
label,
required,
type,
textTransform,
style,
value: propValue
} = this.props;
const { value: stateValue } = this.state;
const element = (
<TextField
inputProps={{ style: { textTransform: textTransform } }}
id={this.id}
disabled={this.isDisabled}
error={error}
focused={focused}
helperText={helperText}
label={label}
onChange={this.handleChange.bind(this)}
required={required}
style={style}
type={type}
defaultValue={propValue}
value={stateValue}
/>
);
return element;
}
private formatValue(value?: string): string | undefined {
const { textTransform } = this.props;
let curValue = value;
if (curValue && textTransform) {
if (textTransform === 'uppercase') {
curValue = curValue.toUpperCase();
} else if (textTransform === 'lowercase') {
curValue = curValue.toLowerCase();
}
}
return curValue;
}
/**
* Callback fired when changing the value.
* @param event Change event
*/
private handleChange(event: React.ChangeEvent<HTMLInputElement>): void {
const value = event.target.value;
this.setState({ value: this.formatValue(value) });
}
}