我有一个围绕ag-Grid的包装器,该包装器接受Definition
数组作为道具。我正在尝试为第一项className
设置Def
中的IDummyComponentProps
字段。通过执行props.Definition[0].className = "clickableCell"
,我可以如下所示实现它,但这是正确的方法吗?
interface IDummyComponentProps {
Definition: Def[];
}
interface Def {
fieldName: string;
className?: string;
}
const DummyComponent: React.FC<IDummyComponentProps> = (props) => {
props.Definition[0].className = "clickableCell";
return (
<div
className="ag-theme-material"
style={{
height: props.Height,
width: props.Width,
}}
>
<AgGridReact
columnDefs={props.Definition}
rowData={someRowData}
/>
</div>
)
}
答案 0 :(得分:1)
不,不是。您正在修改道具,因此违反了将道具保持为只读状态的核心ReactJS要求。如官方文档所述:
无论您将组件声明为函数还是类,它都必须 永远不要修改自己的道具。
https://reactjs.org/docs/components-and-props.html#props-are-read-only
相反,您应该使用{...}
传播算子或Object.create
来制作道具的副本,并对副本进行更改。
答案 1 :(得分:0)
注意:您不能在此组件内部修改组件自己的道具。
如果要使用默认道具,可以这样做,
const DummyComponent: React.FC<IDummyComponentProps> = (props) => {
// Your component code
// ...
}
DummyComponent.defaultProps = {
Definition: [
{ className: "clickableCell" }
]
}
希望获得帮助。