如果目标值为空str,为什么不能将目标值设置为null?
这是我的代码,希望您能帮助我:
class Input extends React.Component {
constructor(props) {
super(props);
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
const fieldValue = event.target.value;
if (!fieldValue) {
event.target.value = null;
}
this.props.onChange(event);
}
render() {
return <input value={this.props.value} onChange={this.onInputChange} />;
}
}
答案 0 :(得分:0)
您应该将值传递给this.props.onChange()
,而不是事件,并且不应将其设置为null。将其设置为空字符串。因此,您应该这样做:
onInputChange(event) {
var fieldValue = event.target.value; // It should be a var, then you can update it
if (!fieldValue) {
fieldValue = "";
}
this.props.onChange(fieldValue);
}
答案 1 :(得分:0)
这是一个老问题,但也许这个答案会对某人有所帮助。如果您正在使用 Material UI 和 Formik,那么这可能会有所帮助:
import TextField from "@material-ui/core/TextField";
import * as React from "react";
export interface TextFieldProps {
className?: string;
disabled?: boolean;
fullWidth?: boolean;
helperText?: string | JSX.Element;
multiline?: boolean;
name: string;
label: string;
onChange?(event: React.ChangeEvent<{ value: string | null }>): void;
required?: boolean;
rows?: number;
type?:
| "text"
| "color"
| "date"
| "email"
| "password"
| "number"
| "tel"
| "time"
| "url"
| "hidden";
value?: string | null;
}
export const NullableTextField: React.FC<TextFieldProps> = (props) => {
const { onChange, value, ...restProps } = props;
const handleChange = React.useCallback<
(event: React.ChangeEvent<{ name?: string; value: string | null }>) => void
>((event) => {
const value = event.target.value;
if (value === "") {
event.target = {
...event.target,
name: event.target.name,
value: null,
};
}
onChange?.(event as React.ChangeEvent<{ value: string | null }>);
}, []);
return (
<TextField
{...restProps}
onChange={handleChange}
value={typeof value === "string" ? value : ""}
variant="outlined"
/>
);
};
顺便说一句。您必须做一些额外的工作来确保空值是 nulls
并且它不是默认行为,这很烦人。