上次使用了參數,讓可以從親層修改子層,但要如何讓子層修改親層呢?
要修改親層的方法,就是在修改的 handler
傳到子層,藉由呼叫 handler
來修改在親層的變數:
function CorrectChildLayer(props) {
const { name, counter, namehandler, counterhandler } = props;
namehandler("睫毛");
counterhandler("101");
return (
<div>
<div>
<h2>Handler 子層</h2>
</div>
<div>
<label>
Hi, {name} 是 {counter} 歲
</label>
</div>
</div>
);
}
export default CorrectChildLayer;
這邊會從親層傳下兩個 handler
:namehandler
、counterhandler
,然後把值放進去到這兩者中,讓他們修改。
為了要讓子曾可以呼叫,因此親層增加這個 component
:
<div>
<CorrectChildLayer
name={name}
counter={counter}
namehandler={handleChangeName}
counterhandler={handleChangeCounter}
></CorrectChildLayer>
</div>
並且實作 handleChangeName
和 handleChangeCounter
這兩個 handler
:
const handleChangeName = (name) => {
const newStr = name;
setName(newStr);
};
const handleChangeCounter = (name) => {
const newStr = name;
setCounter(newStr);
};
這樣就可以由子層進行修改,把名字改成「睫毛」和「101」,這時其他 component
的值也跟著修改囉!
雖然這樣可以修改頁面資訊,不過卻會發生錯誤資訊:
Warning: Cannot update a component (`PropSample`) while rendering a different component (`CorrectChildLayer`). To locate the bad setState() call inside `CorrectChildLayer`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at CorrectChildLayer (http://localhost:3000/static/js/bundle.js:125:5)
這問題是因為值正在轉譯時,值又被更動。詳細資訊與修改方式可以參考:《Warning: Cannot update a component X while rendering a different Y component To locate the bad setState() call inside Y,》