![](/img/trans.png)
[英]React: update component's props from outside of render method without using state
[英]A way to call React component's method from outside (with it's state and props)
我堅持調用我的 clickRemoveHandler。 我的想法是我有兩個組件:第一個 - 呈現 header 的布局、導航和頁腳組件,第二個 - 計算器,它是我的核心組件,具有數據輸入等......在計算器組件中,我有管理 state 的按鈕,所以當我點擊在布局組件 (div) 的任何位置,我需要調用計算器 function 來操作我的按鈕。 代碼如下:
class Layout extends Component {
.....
clickHandler = (event) => {
Calculator.clickRemoveHandler(event);
console.log('Clikced')
};
.....
}
class Calculator extends Component {
state = {
currentServiceClass: null,
hoverIndex: null,
btnClicked: false,
selectedService: null
}
currentCursorPosition = {
el: null,
index: null,
rendered: false
}
static clickRemoveHandler = (event) => {
if ((!event.target.hasAttribute("type")) && (this.state.btnClicked)) {
this.currentCursorPosition = {
el: null,
index: null,
rendered: false
};
this.setState({currentServiceClass: null, hoverIndex: null, btnClicked: false})
}
}
....
}
這些組件中有很多邏輯,因此它們太健壯了,無法發布完整代碼。 但問題是布局中沒有計算器引用,計算器本身是用另一個組件的路由渲染的,所以我不能直接將布局中的任何數據傳遞給計算器。 我想要的是從布局中調用 static clickRemoveHandler。 我猜 static 是一個使 function 成為全局的選項。 所以它有效,但我收到錯誤 TypeError: undefined is not an object (evaluating 'Calculator.state.btnClicked')。 正如我所見,這意味着當調用 clickRemoveHandler 時,它與計算器組件沒有關聯,或者無法訪問其 state 和道具。 問題是我怎樣才能讓它們一起工作? 調用 function 時傳遞計算器 state 還是有其他更優雅的方法?
我建議您描述的情況(不同級別的不同組件需要訪問某些 state 並對其進行操作)使用 React context
。 您也可以查看 state 管理器,例如Redux
或MobX
,但在這種特殊情況下,它會產生開銷,因為您的應用程序不是那么“龐大”。 基本上你需要創建一些單獨的文件夾(你可以稱之為context
),在里面你應該創建上下文本身,導出它並將它包裝在你最上層的組件中,這樣所有的孩子都可以使用它。
您可以在此處找到示例: https://codesandbox.io/s/spring-glitter-0vzul 。
這是文檔的鏈接: https://reactjs.org/docs/context.html
如果您需要,我可以為您提供更多詳細信息
這是一個挑戰,但我做到了:布局組件:
state = {
firstMount: false,
clicked: false,
clickedEvt: null
};
clickHandler = (event) => {
console.log('Clikced')
if (this.state.clickedEvt)
this.setState({clicked: false, clickedEvt: null});
else
this.setState({clicked: true, clickedEvt: event.target}, ()=>{setTimeout(() =>
this.setState({clicked: false, clickedEvt: null})
, 50)})
};
<LayoutContext.Provider value={{
clicked: this.state.clicked,
clickedEvt: this.state.clickedEvt,
handleClick: this.clickHandler
}}>
render() {
return(
<div onClick={(event) => this.clickHandler(event)} className="web">
首先我從 Layout 組件調用 handleClick 作為 onclick 事件,然后從計算器再次調用它
componentDidUpdate() {
if (this.context.clicked) {
this.clickRemoveHandler(this.context.clickedEvt)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.