Reactjs 将默认道具设置为道具数组中第一项的正确方法
我有一个围绕ag网格的包装器,它接受一个Reactjs 将默认道具设置为道具数组中第一项的正确方法,reactjs,ag-grid,Reactjs,Ag Grid,我有一个围绕ag网格的包装器,它接受一个定义数组作为道具。我正试图在Def中为第一项IDummyComponentProps设置className字段。我可以通过执行props.Definition[0].className=“clickableCell”实现如下所示,但这是正确的方法吗 interface IDummyComponentProps { Definition: Def[]; } interface Def { fieldName: string; cla
定义
数组作为道具。我正试图在Def
中为第一项IDummyComponentProps
设置className
字段。我可以通过执行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>
)
}
接口IDummyComponentProps{
定义:Def[];
}
接口定义{
字段名:字符串;
类名?:字符串;
}
常量DummyComponent:React.FC=(道具)=>{
props.Definition[0].className=“clickableCell”;
返回(
)
}
不,不是。您正在修改道具,因此打破了将道具保持为只读的核心要求。正如官方文件所述:
无论将组件声明为函数还是类,它都必须
永远不要修改自己的道具
相反,您应该使用{…}
扩展运算符或对象复制道具。创建
并更改副本。注意:您不能在此组件内修改组件自己的道具
如果你想拥有一个默认道具,你可以这样做
const DummyComponent: React.FC<IDummyComponentProps> = (props) => {
// Your component code
// ...
}
DummyComponent.defaultProps = {
Definition: [
{ className: "clickableCell" }
]
}
const DummyComponent:React.FC=(道具)=>{
//您的组件代码
// ...
}
DummyComponent.defaultProps={
定义:[
{className:“clickableCell”}
]
}
希望这有帮助