我有2个JSX组件
interface Person {
name: string;
lastName: string;
}
<EditableString
isEditing={() => this.getIsEditing(index)}
getStoredValue={() => this.props.items[index].data.item.name}
getEditingValue={() => this.editingRow && this.editingRow.name ? this.editingRow.name : ''}
setValueForEditingRow={
action((value: string) => {
if (this.editingRow) {
this.editingRow.name = value;
}
})
}
/>
<EditableString
isEditing={() => this.getIsEditing(index)}
getStoredValue={() => this.props.items[index].data.item.lastName}
getEditingValue={() => this.editingRow && this.editingRow.lastName? this.editingRow.LastName: ''}
setValueForEditingRow={
action((value: string) => {
if (this.editingRow) {
this.editingRow.lastName = value;
}
})
}
/>
我可以编写一个通用函数,将属性名称作为参数传递吗?在普通的JS中,我可以做类似的事情
this.editingRow[propTitle] = value;
如何在TS中做到这一点?如果有一种方法可以将属性标题缩小到类型或接口,那将是完美的。 (就我而言,将它们限制为'name'
或'lastName'
。
答案 0 :(得分:0)
不知道这是否是最友好,最干净的方法,但是它可以正常工作
public getEditableString = (index: number, editingRowProp: keyof IParentRow, offerViewProp: keyof IOfferView) => <td>
<EditableString
isEditing={() => this.getIsEditing(index)}
getStoredValue={() => this.props.items[index].data.item[offerViewProp] as string}
getEditingValue={() => this.editingRow && this.editingRow[editingRowProp] as string ? this.editingRow[editingRowProp] as string : ''}
setValueForEditingRow={
action((value: string) => {
if (this.editingRow) {
this.editingRow[editingRowProp] = value;
}
})
}
/>
</td>