我有使用MUI中的Select
的组件
import Select from "@material-ui/core/Select";
export class RowSelectComponent extends React.Component {
render() {
const {details, classes, name, displayName, values, updateScenarioDetailsField, readOnly=false} = this.props;
return <FormRow>
<FormLabel>{displayName}</FormLabel>
<FormContent>
<Select
value={details && details[name]}
onChange={(event) => {
updateScenarioDetailsField(name, event.target.value);
}}
className={classes.input}
>
{values && values.map((value, index) =>
<MenuItem key={index} value={value}>{value}</MenuItem>
)}
</Select></FormContent>
</FormRow>;
}
}
我希望能够在变量readOnly
为true时禁用选择。当我这样写时,它可以工作:
<Select
value={details && details[name]}
onChange={(event) => {
updateScenarioDetailsField(name, event.target.value);
}}
className={classes.input}
disabled
>
但是当我尝试这样做时,它就无法工作:
<Select
value={details && details[name]}
onChange={(event) => {
updateScenarioDetailsField(name, event.target.value);
}}
className={classes.input}
disabled={readOnly}
>
如何解决?
答案 0 :(得分:2)
我会这样做。 React确实具有功能:
import React from "react";
import Select from "@material-ui/core/Select";
export default function App() {
const getDisabled = val => {
if (val) return { disabled: true };
return {};
};
return (
<div className="App">
<Select
// You can pass under the readOnly prop
{...getDisabled(true)}
// Other props here
/>
</div>
);
}
因此,以您的示例为例:
export class RowSelectComponent extends React.Component {
getDisabled = val => {
if (val) return { disabled: true };
return {};
}
render() {
const {details, classes, name, displayName, values, updateScenarioDetailsField, readOnly=false} = this.props;
return <FormRow>
<FormLabel>{displayName}</FormLabel>
<FormContent>
<Select
value={details && details[name]}
onChange={(event) => {
updateScenarioDetailsField(name, event.target.value);
}}
{...this.getDisabled(readOnly)}
className={classes.input}
>
{values && values.map((value, index) =>
<MenuItem key={index} value={value}>{value}</MenuItem>
)}
</Select></FormContent>
</FormRow>;
}
}