[英]How to update state of parent by passing a function as props to its children
我有一個父組件 A,它將有一個子組件 B。父組件可以有多個相似的子組件。 我想在父組件中處理這個子組件的數據,因此我將一個函數作為道具傳遞給子組件。 現在,每當子組件發生更改時,我都想重新渲染父組件中的所有組件。 我在父組件中有一個 state,它是一個 object 類型的數組。 每個 object 都將包含一個子組件的數據。 這給了我語法錯誤,如果我更改並嘗試其他方法,它會給我未定義的 componentList 值。
export class Parent extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
componentList: []
};
this.onClick = this.onClick.bind(this);
this.onDataChange = this.onDataChange.bind(this);
}
public onDataChange(index: number) {
return function(data: Data) {
this.setState({
this.state.componentList[index].name = data.name;
});
};
}
在子組件中,我正在更新名稱 onChange,如下所示:
interface Props {
name?: string;
age?: number;
onDataChange: (data: Data) => void;
}
export class Child extends React.Component<Props> {
constructor(props: Props) {
super(props);
this.state = {};
this.onNameChange = this.onNameChange.bind(this);
}
public onNameChange(event) {
this.props.onDataChange({
name: event.target.value,
age: this.props.age
});
}
出現錯誤:“TypeError:無法讀取未定義的屬性‘componentList’”
在發送到道具之前,您是否正在綁定 onDataChange function?
export class parentClass extends Component{
constructor(props){
super(props);
this.onDataChange=this.onDataChange.bind(this);
}
}*/
如果不是,onDataChange 調用中的這個關鍵字指向錯誤的上下文
也更換
this.setState({
this.state.componentList[index].name = data.name;
});
有類似的東西
this.setState({componentList:newComponentList});
由於我的評論似乎對您有所幫助,因此我決定發布答案。 您的onDataChange
function 正在返回另一個 function 以供孩子調用。
public onDataChange(index: number) {
return function(data: Data) { // A function gets returned
this.setState({
this.state.componentList[index].name = data.name;
});
};
}
在孩子內部,您將this
關鍵字的引用綁定到孩子的this
關鍵字:
this.onDataChange=this.onDataChange.bind(this);
這通常沒有錯,但是您想更新父級上的 state,因此您需要對父級 this 的引用。
這可以通過簡單地更改onDataChange
function 的返回“值”來輕松實現。
public onDataChange(index: number) {
// An arrow function always set the this reference to where it's declared correctly,
// therefore this inside the function will reference the parent this.
return (data: Data) => {
this.setState({
this.state.componentList[index].name = data.name;
});
};
}
那么也過時的是: this.onDataChange = this.onDataChange.bind(this);
在您的父構造函數中。
在MDN-Arrow 函數中閱讀此主題可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.