亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React-Native:從父組件調用組件內的函數

React-Native:從父組件調用組件內的函數

紅顏莎娜 2022-11-11 16:19:33
Child.js:export default class Child extends Component {  testFunc = () => {   console.log("test")  }  componentDidMount() {    this.props.onRef(this) }父.js:export default class Parent extends Component { render() {    return (   <>     <Child onRef = {ref => (this.child=ref)}> </Child>     <Button onPress={this.child.testFunc()}></Button>   </>   ) }}我想知道如何從 React Native 的父組件調用子組件中的函數?我嘗試了上面的代碼,我收到錯誤“TypeError undefined is not an object (evaluate '_this.child.testFunc')。當我在這里嘗試建議的解決方案時遇到同樣的錯誤:Call child function from parent component in React Native。有人可以幫我嗎?
查看完整描述

2 回答

?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

在我看來,這是一個糟糕的設計。如果您希望testFunc()在父組件中可用,那么您應該在父組件中定義該函數。

為了在子組件中使用此功能,您可以將此功能傳遞給道具中的子組件。

從 ParentComponent.js 你可以像這樣傳遞這個函數

<ChildComponent func = {testFunc} />

在 ChildComponent.js 中,您可以像這樣回調此函數 this.props.func()


查看完整回答
反對 回復 2022-11-11
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

請試試這個。由于 javascript 語法,在調用 testFunc 時刪除括號。


export default class Parent extends Component {


  render() { 

   return (

   <>

     <Child onRef = {ref => (this.child=ref)}> </Child>

     <Button onPress={this.child.testFunc}></Button>

   </>

   )

  }

 }


查看完整回答
反對 回復 2022-11-11
  • 2 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號